我没有发现任何错误与你的代码,它可能只是表现比预期稍有不同。所以这里是我将如何做到这一点。
一两件事第一:类名应该总是以一个大写字母(不是一个错误,而是一个惯例,有助于理解代码)开始
public static void main(String[] args) throws IOException{
int[] date = new int[10]; // as mentioned above, a fixed size array will limit you - but if 10 is what you want, then this is what you need
int i = 0;
System.out.println("Please enter " + date.length + " numbers"); // just some output to tell the user that the program has started and what to do next
Scanner in = new Scanner(System.in); // perfect
// if you absolutely want your array filled, check if you reached the end of your input to avoid IndexOutOfBoundsExceptions.
// in.hasNext() will check for ANY input, which makes it easier to handle unwanted user input
while(i < date.length && in.hasNext()){
if(in.hasNextInt()){ // here you check if the input starts with a number. Beware that "1 w 2" is valid too!
date[i] = in.nextInt();
i++;
}else{
// this is to advise the user of an input error
// but more importantly, in.next() will read the invalid input and remove it from the inputstream. Thus your scanner will continue to read the input until it ends
System.out.println("sorry \"" + in.next() + "\" is not a valid number");
}
}
System.out.println("your input:");
for(i = 0; i < date.length; i++){ // you don't need any advanced loops, it is perfectly fine to use indexed loops. Just try to make your break condition more dynamic (like checking the length of the array instead of a constant value)
System.out.println(date[i]);
}
}
这既不是一个解决办法,也不是最好的办法做到这一点。我只是想告诉你如何引导你的用户并处理不需要的输入。
编辑:概括地说,这些事情应该考虑:
- 不作任何假设您的用户的情报,他/她可以输入任何东西:
1 two 2.3 , 4 . @¹"
- 肯定您需要
10
数字,否则使用不同大小的数组或列表(如果您不知道需要多少个数字)
- 也许用户不想输入尽可能多的数字并且想要退出早些时候(
if(in.next().equalsIgnoreCase("q")
可以做的技巧)
- 你接受任何整数?甚至是负面的?
- 你应该接受
long
还是BigInteger
?
- 浮点数呢?
- 以及您想如何处理错误?忽略它,用默认值替换它,退出循环甚至程序?
这里有一些例子运行:
Please enter 10 numbers
1
2
3 4 5 6 7 8 9
10
your input:
1
2
3
4
5
6
7
8
9
10
Please enter 10 numbers
1 2 3 4 5 6 7 8 9 10
your input:
1
2
3
4
5
6
7
8
9
10
Please enter 10 numbers
1 2 3 4 r 5 6 7 8 9 10
sorry "r" is not a valid number
your input:
1
2
3
4
5
6
7
8
9
10
Please enter 10 numbers
1 2 3 4 5 6 7 8 9 10 11
your input:
1
2
3
4
5
6
7
8
9
10
是什么'while'循环在这里做什么? – emotionlessbananas
使用调试器,你会发现什么是发生的 – Jens
while循环用于从控制台获取输入@AsteriskNinja – user3797489