如何在Java中的嵌套循环内突破if语句 [英] How to break through if statement inside a nested loop in java

查看:104
本文介绍了如何在Java中的嵌套循环内突破if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在解决java上的问题时,我发现无法突破位于for循环内的if语句,而此for循环位于另一个if语句内.代码片段如下:

While solving a problem on java I am finding trouble breaking through the if statement which is inside a for loop and this for loop is inside another if statement. The code fragment is as below:

package experment;
public class myclass_2{
 public static void main(String[] args){
  int t;
  int remaining;
  boolean is_undertaker_dead = false;
  Scanner s = new Scanner(System.in);
  System.out.println("hey");
  t = s.nextInt();
  for(int i=0; i<t; i++)
  {
      String S = Integer.toString(s.nextInt());
      char c[] = S.toCharArray();
      for(int j=0; j<c.length; j++)
      {
          if(c[j]=='2')
          {
              remaining = c.length-j;
              for(int a=j; a<c.length; a++)
              {
                  if(remaining<c.length)
                      {
                      remaining=0;
                  }
                  if(c[j+remaining]=='1')
                  {
                     is_undertaker_dead=true;
                     break;
                  }
                  remaining--;
              }
          }
      }
      if(is_undertaker_dead==true)
      { 
          System.out.println("The Streak is broken!");
      }
      else
      {
          System.out.println("The streak");
      }
  }
 }

一旦要调用break语句,我想在所有for循环之外中断.我知道这只是打破了if语句,但循环仍在继续.我也尝试使用我在stackoverflow和google上找到的label方法,但是它们以某种方式不起作用并使我更加困惑.预先感谢您的支持,这非常重要!

I want to break outside of all the for loops once the break statement is called. I know this just break out of the if statement but the loop still continues. I also tried using the label method which I find on stackoverflow and google, but they somehow didn't work and confused me even more. Thank you in advance for your support, it means a lot!

推荐答案

首先,break不会中断if语句,它会中断循环,在您的情况下是第二个for循环.

Firstly, break doesn't break out of if statement, it breaks out of loops, in your case second for loop.

在您的代码中,break脱离了内部for循环.要突破外部for循环,只需在外部循环的右括号之前放置以下条件

In your code, break breaks out of inner for loop. To break out of outer for loop, simply put below condition, just prior to the closing bracket of the outer loop

if (is_undertaker_dead)
    break;

这篇关于如何在Java中的嵌套循环内突破if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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