This may sound silly but I couldn't find an answer by googling it.

When using a for loop in it's simplest form I can add conditions to break the loop in the for statement. example:

for(int i=0; i<100 && condition2 && condition3; i++){
    //do stuff
}

When using an object for loop like this:

for(String s:string_table){
    //do stuff
}

how can i add a condition to break the loop? I'm talking about adding conditions in the for statement. I know I can add the condition inside //do stuff part and break from there.

有帮助吗?

解决方案

You cannot do that you have to go by putting the if statements in the for loop.

其他提示

You cannot add anything else to the () part of the "enhanced for" statement. JLS § 14.14.2:

The enhanced for statement has the form:

for ( FormalParameter : Expression ) Statement

The type of the Expression must be Iterable or an array type.

(The "FormalParameter" means a variable declaration.)

The break; statement is the only way:

for (String s : string_table) {
    if (condition) break;
    // ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top