java中使用goto语句_java – 如何正确使用goto语句

我正在上高中AP计算机科学课.

我决定把一个goto语句放到我们的一个实验室中来玩,但我得到了这个错误.

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

Syntax error on token "goto", assert expected

restart cannot be resolved to a variable

at Chapter_3.Lab03_Chapter3.Factorial.main(Factorial.java:28)

我在Stackoverflow上转到了一个goto问题,以了解如何正确地完成它,并且我完全按照其中一个答案进行了演示.我真的不明白为什么编译器需要一个断言语句(至少这是我认为它想要的),我也不知道如何使用断言.它似乎想要重启部分goto restart;作为变量,但重新启动只是一个标签,将程序拉回到第10行,以便用户可以输入有效的int.如果它想重新启动变量,我该怎么做?

import java.util.*;

public class Factorial

{

public static void main(String[] args)

{

int x = 1;

int factValue = 1;

Scanner userInput = new Scanner(System.in);

restart:

System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");

int factInput = userInput.nextInt();

while(factInput<=0)

{

System.out.println("Enter a nonzero, nonnegative value to be factorialized.");

factInput = userInput.nextInt();

}

if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.

{

System.out.println("The number you entered is not valid. Please try again.");

goto restart;

}

while(x<=factInput)

{

factValue*=x;

x++;

}

System.out.println(factInput+"! = "+factValue);

userInput.close();

}

}

解决方法:

正如所有答案所指出的那样 – 一个Java中的保留字,并没有在语言中使用.

restart:被称为标识符,后跟冒号.

如果您希望实现类似的行为,您需要注意以下几点:

outer: // Should be placed exactly before the loop

loopingConstructOne { // We can have statements before the outer but not inbetween the label and the loop

inner:

loopingConstructTwo {

continue; // This goes to the top of loopingConstructTwo and continue.

break; // This breaks out of loopingConstructTwo.

continue outer; // This goes to the outer label and reenters loopingConstructOne.

break outer; // This breaks out of the loopingConstructOne.

continue inner; // This will behave similar to continue.

break inner; // This will behave similar to break.

}

}

我不确定我是否应该像我已经说的那样说话.

标签:java,loops,goto

来源: https://codeday.me/bug/20190928/1826768.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值