23

I want to break a while loop of the format below which has an if statement. If that if statement is true, the while loop also must break. Any help would be appreciated.

while(something.hasnext()) {
   do something...
   if(contains something to process){
      do something
      break if condition and while loop
   }
}
3
  • 3
    You said the answer in your question! Commented May 8, 2014 at 19:40
  • break if loop something do while loop confused me. I thought there are two loops. Commented May 8, 2014 at 19:42
  • you can't say if(true){break;}. Commented May 8, 2014 at 20:09

3 Answers 3

54

The break keyword does exactly that. Here is a contrived example:

public static void main(String[] args) {
  int i = 0;
  while (i++ < 10) {
    if (i == 5) break;
  }
  System.out.println(i); //prints 5
}

If you were actually using nested loops, you would be able to use labels.

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

7 Comments

@Codelearn14 You keep saying that, but no matter how many times you say it it will still be false.
@Codelearn14 Can you post code example which will prove what you are saying? Maybe condition of if is never fulfilled preventing break from being invoked.
Yeah i think the same too. My bad sorry and thanks for the help
@Codelearn14 I have added a simple example that you can run to confirm the behaviour.
I really wish @Codelearn14 didn't delete their comments because this argument looks hilarious.
|
9

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

Comments

7
while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

Comments

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.