如何退出两个嵌套循环 [英] How to exit two nested loops

查看:379
本文介绍了如何退出两个嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用java很长一段时间了,但我在循环中的教育有点缺乏。我知道如何创建java中存在的每个循环,并打破循环。但是,我最近想到了这个:

I have been using java for quite some time, yet my education in loops is somewhat lacking. I know how to create every loop that exists in java and break out of the loops as well. However, I've recently thought about this:


说我有两个嵌套循环。我可以只使用一个 break 语句来打破这两个循环吗?

Say I have two nested loops. Could I break out of both loops using just one break statement?

这是我目前所拥有的。

int points = 0;
int goal = 100;
while (goal <= 100) {
   for (int i = 0; i < goal; i++) {
      if (points > 50) {
         break; //for loop ends, while loop does not
      }
   //I know I could put a 'break' statement here and end the while loop but I want to do it using just one 'break' statement
   points += i;
   }
}

有没有办法实现这个目标?

Is there any way to achieve this?

推荐答案

在java中,您可以使用标签指定要断开/继续的循环:

In java you can use a label to specify which loop to break/continue:

mainLoop:
while (goal <= 100) {
   for (int i = 0; i < goal; i++) {
      if (points > 50) {
         break mainLoop;
      }
      points += i;
   }
}

这篇关于如何退出两个嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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