Reputation:
So I'm aware that you can create a for loop with several conditions:
for (int i=0; i<5&&i%2!=1; i++){
//Do something
}
Can the same thing be done in a iterator loop, if so, could an example be given:
String[] arrayofstrings = {"Hello", "World"};
for (String s : arrayofstrings){
//Do something
}
Upvotes: 1
Views: 5034
Reputation: 2188
No you can't add conditions in the foreach
loop. It can only be used to iterate through the elements.
It can only be like:
for (String s : arrayofstrings){
//Do something
}
and it can't be like:
for (String s : arrayofstrings && some condition){
//Do something
}
Upvotes: 1
Reputation: 8338
Uh, your question is very unclear here.
The first example is a forloop, where the middle section with the conditions is the condition that checks when to stop. Basically, you can think of it as a while loop.
for(int i = 0; i < 5 && i != 3; i++) {
doSomething();
}
is the same as
int i = 0;
while(i < 5 && i != 3) {
doSomething();
i++;
}
The second one just iterates through the items in your list. There is no sort of condition...
String[] arrayofstrings = {"Hello", "World"};
for(String s : arrayofstrings) {
System.out.prinltn(s);
}
Will print out
Hello
World
What sort of condition would you want here. It is basically the equivalent of doing
String[] arrayofstrings = {"Hello", "World"};
for(int i = 0; i < arrayofstrings.length; i++) {
System.out.println(arrayofstrings[i]);
}
There is no condition being evaluated or a time to stop...
Upvotes: 0