我沒有發現任何錯誤與你的代碼,它可能只是表現比預期稍有不同。所以這裏是我將如何做到這一點。
一兩件事第一:類名應該總是以一個大寫字母(不是一個錯誤,而是一個慣例,有助於理解代碼)開始
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