问题
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
}
}
回答1:
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.
回答2:
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?");
}
回答3:
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.
来源:https://stackoverflow.com/questions/23550985/how-to-break-a-while-loop-from-an-if-condition-inside-the-while-loop