How can you refer to the index of an array in the foreach?
My code
String[] name = { "hello", "world" };
for ( int k : name[k] ) {
--- cut ---
}
I expecting that the foreach -loop will
1. set k = 0 in first iteration so that name[0] works correctly
2. set k = 1 in the next iteration...
I get the error message
foreach not applicable to expression type
That's because the index is not available when using the foreach
syntax. You have to use traditional iteration if you need the index:
for (int i =0; i < names.length; i++) {
String name = names[i];
}
If you do not need the index, the standard foreach
will suffice:
for (String name : names) {
//...
}
EDIT: obviously you can get the index using a counter, but then you have a variable available outside the scope of the loop, which I think is undesirable
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