问题
Why does think not work? It just prints zeros. However it works when I use a normal for loop with an index value 'i' and using 'a[i]' inside the body of the loop.
The problem is not with the printing loop, as it does not print the values, even with a normal for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] a = new int[5];
for (int i : a)
{
System.out.println("Enter number : ");
i=s.nextInt();
}
System.out.println("\nThe numbers you entered are : \n");
for (int i : a)
{
System.out.println(i);
}
}
}
回答1:
When you access the element using enhanced for-loop: -
for (int i : a)
{
System.out.println("Enter number : ");
i=s.nextInt();
}
Here, int i is a copy of element in the array. When you modify it, the change will not get reflected in the array. That's why the array elements are 0.
So, you need to iterate using traditional for-loop and access the array elements on that index to assign values to it.
Even if your array was an array of some reference, it would still not work. That's because, the variable in a for-each is not a proxy for an array or Collection reference. For-each assigns each entry in the array to the variable in the loop.
So, your enhanced for-loop: -
for (Integer i: arr) {
i = new Integer();
}
is converted to: -
for (int i = 0; i < arr.length; i++) {
Integer i = arr[i];
i = new Integer();
}
So, the initialization of i in the loop, is not reflected in the array. And thus the array elements are null.
Workarond: -
use traditional for loop: -
for (int i = 0; i < a.length; i++) { a[i] = sc.nextInt(); }
回答2:
Your first for loop should be a "classical" for loop :
for (int i = 0; i < a.length; i++) {
a[i] = s.nextInt();
}
回答3:
i=s.nextInt();
This is assigning to a local variable i, not the array element. Essentially,
for (int i : a) {
// body
}
is same as
for (int index = 0; index < a.length; index++) {
int i = a[index];
// body
}
So whatever you assign to i does not affect the array.
回答4:
the statement
i=s.nextInt()
Ask yourself :- what are you doing here?
you are taking input from user. BUT where are you storing it? inside i? which will get overwritten with each iteration.
Also i is local scoped to for loop. So it doesnt exists outside the containing loop.
So you will get 0... 0 ..0 as output.
The solution :
for (int i=0;i<a.length;i++) {
a[i] = s.nextInt();
}
store the values user input inside the array.
回答5:
You should store the values you get from s.nextInt();, this can be achieved by :
int j = 0;
for (int i : a){
System.out.println("Enter number : ");
a[j++]=s.nextInt();
}
This should work.
来源:https://stackoverflow.com/questions/13252318/enhanced-for-loop-does-not-work-with-scanner-inside-loop-body