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