跳出 Java 中的 for 循环 [英] Breaking out of a for loop in Java

查看:29
本文介绍了跳出 Java 中的 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my code I have a for loop that iterates through a method of code until it meets the for condition.

有没有办法摆脱这个 for 循环?

Is there anyway to break out of this for loop?

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

So if we look at the code below, what if we want to break out of this for loop when we get to "15"?

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

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

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

I've tried the following to no avail:

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("
");
          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("
");
             if (x = 15) {
                 break breakLoop;
             }
      }
   }
}

我可以实现我想要的唯一方法是跳出 for 循环,我不能用它来替代一段时间、do、if 等语句.

The only way I can achieve what I want to is by breaking out of a for loop, I cannot subsitute it for a while, do, if etc statement.

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

This was provided only as an example, this isn't the code I'm trying to get it implemented into. I have now solved the problem by placing multiple IF statements after where each loop initilizes. Before it would onlu jump out of one part of the loop due to lack of breaks;

推荐答案

break; 是您摆脱任何循环语句(例如 for)所需要的whiledo-while.

break; is what you need to break out of any looping statement like for, while or do-while.

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

In your case, its going to be like this:-

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

这篇关于跳出 Java 中的 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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