I have the following code that gets an element from the terminal with the Scanner class and adds it to a shopping cart array. It works fine, except that when I try to print the cart it'll show the unfilled positions of the array as "null". I digged over some topics here and someone sugested to create the first array with blank spaces for each of the 5 position (like String[] test = new String[]{"","","","",""};
, but that didn't work. What should I do to "fix" this?
import java.util.Arrays;
import java.util.Scanner;
public class ex03 {
public static void main(String[] args) {
Scanner frutas = new Scanner(System.in);
String[] nomesFrutas = new String[5];
System.out.println("Insira a sua lista de compras.");
for (int i = 0; i <= nomesFrutas.length; i ) {
nomesFrutas[i] = frutas.next();
System.out.println("As frutas no seu carrinho são: \r\n " Arrays.toString(nomesFrutas));
}
}
}
CodePudding user response:
it'll show the unfilled positions of the array as
null
There's a couple ways to avoid uninitialized elements to show up.
A quick and lazy way would be to use the built-in functionality of the Arrays
utility class. You can print a copy of the part that was populated and print it.
By the way, there's a bug in your code: condition i <= nomesFrutas.length
would produce an ArrayIndexOutOfBounds
during the very last iteration because nomesFrutas[i]
would refer to an illegal index.
That's how you can make use of the utility method Arrays.copyOf()
:
for (int i = 0; i < nomesFrutas.length; i ) {
nomesFrutas[i] = frutas.next();
System.out.println("As frutas no seu carrinho são: \r\n "
Arrays.toString(Arrays.copyOf(nomesFrutas, i 1)));
}
There are several drawbacks of this solution:
- a new array needs to be allocated in memory at each iteration step just in order to print non-null elements (it's a good habit to be mindful while your action require creating new objects that are immediately thrown away, especially when it can be avoided);
- as I've said it's a "lazy" way, because it doesn't require implementing things yourself, try not to overuse such ready-to-go options when you're learning.
Another approach would be to create your own method responsible for displaying a range of array elements:
for (int i = 0; i < nomesFrutas.length; i ) {
nomesFrutas[i] = frutas.next();
System.out.println("As frutas no seu carrinho são: \r\n ");
display(nomesFrutas, i 1);
}
public static void display(String[] arr, int len) {
if (len < 1) return;
System.out.print('[');
for (int i = 0; i < len; i ) {
System.out.print(arr[i]);
if (i < len - 1) System.out.print(", ");
else System.out.print(']');
}
}
Fill free to play around with this solution and adjust it in whatever way you see fit.