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:
for (counterOne = 0; counterOne < 5; counterOne++)
From this section of the Java Language Specification about enhanced for
-loops:
The enhanced for statement has the form:
EnhancedForStatement:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement
EnhancedForStatementNoShortIf:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) StatementNoShortIf
Note that the type declaration UnannType
must be present in the for
loop. Therefore, you should write the loop as follows:
for (int z : x) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With