怎么用break实现跳转?

kingfighter_han 2003-07-13 09:05:23
我的
public class BreakErr{
public static void main(String args[]){
outerloop:
for(int i=0;i<3;i++){
System.out.print("pass"+i+":");
}
for(int j=0;j<100;j++){
if(j == 10)
break outerloop;
System.out.print(j+"");
}
}
}
在编译时出现undefined label: outerloop 而
public class Factorial
{
public static void main(String[] args)
{
long limit = 20; // to calculate factorial of integers up to this value
long factorial = 1; // factorial will be calculated in this variable

// Loop from 1 to the value of limit
OuterLoop:
for(int i = 1; i <= limit; i++)
{
factorial = 1; // Initialize factorial
for(int j = 2; j <= i; j++)
{
if(i > 10 && i % 2 == 1)
continue OuterLoop; // Transfer to the outer loop
factorial *= j;
}
System.out.println(i + "!" + " is " + factorial);
}
}
}
却能顺利通过,那为大哥能帮以下我!
...全文
70 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
javaVegetable 2003-07-13
  • 打赏
  • 举报
回复
经过测试发现你的第一段代码的i循环和j循环并没有嵌套。所以break 后调不到outerloop标号,所以报错。
应该改为:
public class BreakErr{
public static void main(String args[]){

//outerloop:
for(int i=0;i<3;i++){
System.out.print("pass"+i+":");
}
outerloop:
for(int j=0;j<100;j++){
if(j == 10)
break outerloop;
System.out.print(j+"");
}
}
}

现在编译通过
kofwr 2003-07-13
  • 打赏
  • 举报
回复
这个label必须用在大于一个以上的循环内,你这个不是循环嵌套,不行
beyondii 2003-07-13
  • 打赏
  • 举报
回复
break是跳出整个循环,继续执行程序.
continue是跳出当前循环,开始下一次循环

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧