Can someone comment me on the following question:
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 if we do not use counterOne after the loop ends.
In the foreach loop, we also declare counterTwo outside the loop, and then use it only inside the loop. However, in this case, an error occurs:
"Exception in thread" main "java.lang.RuntimeException: Uncompilable source code - cannot find character symbol: class counterTwo location: class package1.Loopy"
Can you help me understand why?
The only difference between them is that counterOne initialized to zero, and then the values ββare assigned step by step (less than 5).
In the foreach loop, counterTwo assigned one after another, each element of the array.
The program works if we do this in the second loop: for(int counterTwo : myArray) , and the first to work in both cases:
- existing
for (counterOne = 0; counterOne < 5; counterOne++)
source share