[英]Printing an array with input from user. Returning first value a zero?
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. 我不确定自己做了什么,但我的目标是接受用户的10个数字并将其存储到数组中。 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));
}
}
}
Your array should be sized to 10
(and your loop test should also be 10
, or better - use the array length
). 您的数组大小应为
10
(并且循环测试的大小也应为10
或更好-使用数组length
)。 You should use braces, it helps prevent subtle bugs. 您应该使用花括号,它有助于防止细微的错误。 And I see no reason to discard the first
int
. 而且我认为没有理由放弃第一个
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));
you've defined an array of 9
elements, not 10
. 您定义了
9
元素组成的数组,而不是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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.