0

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.

1
  • 1
    You can't do that... The foreach construct is "fixed". Commented Feb 16, 2014 at 14:12

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

that's too bad. it would make it much easier
@user3051067 It wouldn't. It would just make it one line shorter. If it upsets you that much, put the if-break on the same line as the opening brace and pretend it's part of the for syntax.
1

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;
    // ...
}

3 Comments

+1. Now can you please explain why did you choose this avatar? :D
I would use if (!condition2 || !condition3) ... instead of if (condition) to match OP's code better.
@Boann That's the last thing that I though about LOL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.