[英]How to break a while loop from an if condition inside the while loop?
我想打破下面格式的while循環,它有一個if語句。 如果if語句為true,則while循環也必須中斷。 任何幫助,將不勝感激。
while(something.hasnext()) {
do something...
if(contains something to process){
do something
break if condition and while loop
}
}
break
關鍵字就是這樣做的。 這是一個人為的例子:
public static void main(String[] args) {
int i = 0;
while (i++ < 10) {
if (i == 5) break;
}
System.out.println(i); //prints 5
}
如果您實際使用的是嵌套循環,則可以使用標簽 。
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
只需使用break語句;
例如:這只是打印“Breaking ...”
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}
“if”不是循環。 只需在“if”中使用break,它就會突破“while”。
如果您需要使用真正的嵌套循環,Java具有標記中斷的概念。 你可以在循環之前放置一個標簽,然后使用標簽的名稱來斷開參數。 它將在標記的循環之外打破。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.