如何正确使用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我已经说过的话

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章