如何从while循环内的if条件中断while循环? [英] How to break a while loop from an if condition inside the while loop?

查看:290
本文介绍了如何从while循环内的if条件中断while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想中断以下格式的while循环,该循环下面带有if语句。如果if语句为true,则while循环也必须中断。

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
   }
}


推荐答案

break 关键字正是这样做的。这是一个人为的示例:

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.

这篇关于如何从while循环内的if条件中断while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆