![](/img/trans.png)
[英]Java read each lines of numbers from text file using Scanner class, finding max value
[英]I have to read numbers by using Scanner and for each
我在互聯網上找不到任何提示。 幾乎提到“每個”時都說“不能更改數組上分配的值”是不可能的嗎? 我的代碼是這樣的:
Scanner in = new Scanner(System.in);
int[] arr = new int[5];
for(int i : arr)
i = in.nextInt();
我想使用“ for each”並使用Scanner類讀取數字,請幫助我。
使用簡單的for
循環,然后將讀取的數字添加到數組的第i
個位置:
Scanner in = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
在您的特定情況下使用增強的for
循環沒有多大意義,因為數組最初是空的。 但是,您可以使用它遍歷創建的數組,即:
for (int i : arr) {
System.out.println(i);
}
就這么簡單:-
Scanner in = new Scanner(System.in);
int[] arr = {0, 1, 2, 3, 4};
for (int i : arr) {
arr[i] = in.nextInt();
}
但是通過上面的陳述João Silva
,你應該使用for-each循環只迭代已初始化數組,而不是將其初始化..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.