我正在上高中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
的问题,想找到正确的用法,并且我按照答案中演示的方式做了。但我真的不明白编译器为什么要求有一个assert
语句(至少我认为是这样),也不知道如何使用assert
。它似乎希望goto restart;
中的restart重新启动部分是一个变量,但是restart只是一个标签,将程序带回到第10行,以便用户可以输入一个有效的int
。如果它要求restart成为一个变量,那我该怎么办呢?
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();
}
}
goto
是Java中的一个关键字,但它没有功能,并且会导致编译错误(正如您在问题中所指出的)。 - DwBgoto
的方式。换句话说,不仅是为了跳出循环 - 而是任何他们想要的地方,到处都是。你听说过“意大利面代码”这个术语吗?如果你画出goto
开始和结束的线,它看起来像一盘意大利面。 (附言:我已经编程很长时间了,记得当时意大利面代码是我和周围所有人编写程序的方式。我们还不知道更好的方法。) - ajb