如何正确使用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)

goto问了一个关于Stackoverflow

的问题,以找出如何正确执行它,并且我所做的完全如答案之一所示。我真的不明白为什么编译器想要一个assert语句(至少这是我假设的要求),我也不知道如何使用assert。似乎希望重新启动的部分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();

}

}

回答:

正如所有答案所指出的那样goto-语言中有一个保留字,Java并且未在该语言中使用。

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

如果您希望实现某些similar行为,则需要注意以下几点:

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.

}

}

我不确定是否应该说similar我已经说过的话。

以上是 如何正确使用goto语句 的全部内容, 来源链接: utcz.com/qa/424218.html

回到顶部