Declaring variables outside foreach loops in Java
Someone can please tell me the following:
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 as long as we do not 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:
Can you help me understand why?
The only difference between the two is that counterone is initialized to zero, and then the value is gradually specified (less than 5)
In the foreach loop, countertwo is allocated one by one, each array item
If we make adjustments in the second for loop, the program can work: for (int countertwo: myArray), and the first applies to two cases:
>Existing > for (counterone = 0; counterone < 5; counterone)
Solution
Starting with this section of the Java language specification, about the enhanced for loop:
Note that the type declaration unanntype must exist in the for loop Therefore, you should write the loop as follows:
for (int z : x) {