java中if语句的嵌套,如何在Java中的嵌套循环内突破if语句

博客作者在解决 Java 问题时遇到了困境,涉及到嵌套的 if 和 for 循环。他们想要在满足特定条件时跳出所有循环,但发现 break 只能跳出最内层循环。解决方案建议在外部循环结束前添加条件检查,一旦满足条件就跳出整个循环。这有助于理解 Java 中 break 语句的工作原理及其在控制流程中的应用。
摘要由CSDN通过智能技术生成

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

{

String S = Integer.toString(s.nextInt());

char c[] = S.toCharArray();

for(int j=0; j

{

if(c[j]=='2')

{

remaining = c.length-j;

for(int a=j; a

{

if(remaining

{

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!

解决方案

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值