打破Java中的for循环[关闭]

2024-03-31

在我的代码中,我有一个 for 循环,它迭代代码方法,直到满足 for 条件。

有没有办法跳出这个for循环?

因此,如果我们看下面的代码,如果我们想在到达“15”时跳出这个 for 循环怎么办?

public class Test {

   public static void main(String args[]) {

      for(int x = 10; x < 20; x = x+1) {
         System.out.print("value of x : " + x );
         System.out.print("\n");
      }
   }
}

Outputs:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

我已尝试以下方法但无济于事:

public class Test {

   public static void main(String args[]) {
      boolean breakLoop = false;
      while (!breakLoop) {
          for(int x = 10; x < 20; x = x+1) {
             System.out.print("value of x : " + x );
             System.out.print("\n");
          if (x = 15) {
              breakLoop = true;
          }
          }
      }
   }
}

我尝试过一个循环:

public class Test {

   public static void main(String args[]) {
      breakLoop:
          for(int x = 10; x < 20; x = x+1) {
             System.out.print("value of x : " + x );
             System.out.print("\n");
             if (x = 15) {
                 break breakLoop;
             }
      }
   }
}

我实现我想要的唯一方法是打破 for 循环,我不能用 while、do、if 等语句替换它。

Edit:

这仅作为示例提供,这不是我试图将其实现的代码。我现在通过在每个循环初始化之后放置多个 IF 语句解决了这个问题。之前它会因为缺少中断而跳出循环的一部分;


break;是你需要打破任何循环语句的东西,比如for, while or do-while.

在你的情况下,它会是这样的:-

for(int x = 10; x < 20; x++) {
         // The below condition can be present before or after your sysouts, depending on your needs.
         if(x == 15){
             break; // A unlabeled break is enough. You don't need a labeled break here.
         }
         System.out.print("value of x : " + x );
         System.out.print("\n");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

打破Java中的for循环[关闭] 的相关文章

随机推荐