Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

label - How to break through if statement inside a nested loop in java

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");
      }
  }
 }

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...