How to break a while loop from an if condition inside the while loop?

后端 未结 3 983
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 11:12

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.

3条回答
  •  悲&欢浪女
    2020-12-20 11:55

    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.

提交回复
热议问题