Java 如何从while循环内的if条件中断while循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23550985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to break a while loop from an if condition inside the while loop?
提问by Coder2019
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 循环,它有一个 if 语句。如果 if 语句为真,while 循环也必须中断。任何帮助,将不胜感激。
while(something.hasnext()) {
do something...
if(contains something to process){
do something
break if condition and while loop
}
}
采纳答案by assylias
The break
keyword does exactly that. Here is a contrived example:
该break
关键字正是这么做的。这是一个人为的例子:
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.
如果您实际上使用嵌套循环,则可以使用 labels。
回答by Ernest Friedman-Hill
An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".
“如果”不是循环。只需在“if”中使用break,它就会跳出“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.
如果您需要使用真正的嵌套循环,Java 有标记中断的概念。您可以在循环之前放置一个标签,然后使用标签的名称作为要中断的参数。它将在标记循环之外中断。
回答by rahul pasricha
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
只需使用 break 语句;
For eg:this just prints "Breaking..."
例如:这只是打印“Breaking ...”
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}