在我的代码中,我有一个for循环遍历代码的一个方法,直到满足for条件。突破Java中的for循环
有没有办法打破这个循环?因此,如果我们看下面的代码,如果我们想要在达到“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("\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循环,我不能将它暂时搁置一段时间,如果等等。
编辑:
这是作为一个例子仅供,这不是我想要把它落实到代码。我现在已经通过在每个循环初始化之后放置多个IF语句来解决这个问题。之前它会因缺少休息而跳出循环的一部分;
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html – 2013-03-07 15:36:16
您的要求还不清楚。你想什么时候打破循环? – 2013-03-07 15:37:31
对不起,我稍微冲了一下这个例子。现在全部排序 - 原因是打破了一个循环,然后进入另一个循环。需要多个IF&BREAK! – silverzx 2013-03-07 15:45:58