Reputation: 33
I'm not exactly sure what I have done but my goal is to accept 10 numbers from the user and store them into an array. In which I can then print back out in order received. I believe I have accomplished that with the exception of the first value is defaulting to zero in the output and I am not sure how to fix that. Any help?
package array;
import java.util.Scanner;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] a = new int[10];
Scanner input = new Scanner(System.in);
System.out.println("Please enter ten numbers: ");
input.nextInt();
for(int j=0; j<10; j++)
a[j]=input.nextInt();
System.out.println("Your number list is:");
System.out.println(Arrays.toString(a));
}
}
}
Upvotes: 0
Views: 468
Reputation: 56423
you've defined an array of 9
elements, not 10
.
change this:
int[] a = new int[9];
to this:
int[] a = new int[10];
also, change this:
for(int j = 0; j < 9; j++)
to this:
for(int j = 0; j < a.length; j++)
Lastly but not least these two statements should not be inside the loop:
System.out.println("Your number list is: ");
System.out.println(Arrays.toString(a));
place them outside the loop.
for (int j = 0; j < a.length; j++) {
a[j] = input.nextInt();
}
System.out.println("Your number list is:");
System.out.println(Arrays.toString(a));
Upvotes: 2
Reputation: 201439
Your array should be sized to 10
(and your loop test should also be 10
, or better - use the array length
). You should use braces, it helps prevent subtle bugs. And I see no reason to discard the first int
. Putting it all together like,
int[] a = new int[10];
Scanner input = new Scanner(System.in);
System.out.println("Please enter ten numbers: ");
for (int j = 0; j < a.length; j++) {
a[j] = input.nextInt();
}
System.out.println("Your number list is: ");
System.out.println(Arrays.toString(a));
Upvotes: 2