Can someone please enlighten me on the following matter:
public class Loopy {
public static void main(String[] args)
{
int[] myArray = {7, 6, 5, 4, 3, 2, 1};
int counterOne;
for (counterOne = 0; counterOne < 5; counterOne++) {
System.out.println(counterOne + " ");
}
System.out.println(counterOne + " ");
int counterTwo = 0;
for (counterTwo : myArray) {
System.out.println(counterTwo + " ");
}
}
}
In the for-loop, we declare counterOne outside the loop and use it inside the loop. This is correct, so long as we don't use counterOne after the loop is completed.
In the foreach-loop, we also declare counterTwo outside the loop and then use it only inside the loop. However, an error is thrown in this case:
"Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol symbol: class counterTwo location: class package1.Loopy"
Can you help me understand why?
The only difference between the two, is that counterOne is initialized to zero, and then is assigned values incrementally (smaller than 5).
In the foreach loop, counterTwo is assigned one by one, each array item.
The program works if we make this adjustment in the second for loop: for(int counterTwo : myArray), while the first for works in both cases:
- the existing one
for (counterOne = 0; counterOne < 5; counterOne++)