Java 如何正确使用goto语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26430630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:29:03  来源:igfitidea点击:

How to use goto statement correctly

javaloopsgoto

提问by Ungeheuer

I am taking my high school AP Computer Science class.

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

I decided to throw a gotostatement into a one of our labs just to play around, but I got this error.

我决定在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)

I went to a gotoquestion on Stackoverflow to find out how to do it properly, and I did exactly as was demonstrated in one of the answers. I really don't understand why the compiler wants an assertstatement (at least that's what I assume it wants), nor do I have any idea how to use assert. It seems to want the restart part of goto restart;to be a variable, but restart is just a label that pulls the program back up to line 10 so that the user can enter a valid int. If it wants restart to be a variable, how do I do that?

我去了一个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();
    }
}

采纳答案by Tirath

As already pointed out by all the answers goto- a reserved word in Javaand is not used in the language.

正如所有答案所指出的那样goto- 保留字 inJava和 未在该语言中使用。

restart:is called an identifier followed by a colon.

restart:被称为标识符后跟一个冒号。

Here are a few things you need to take care of if you wish to achieve similarbehavior -

如果你想实现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.
    }
}

I'm not sure of whether should I say similaras I already have.

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

回答by Sizik

gotodoesn't do anything in Java.

goto在 Java 中不做任何事情。

回答by Aditya Singh

The Java keyword listspecifies the goto keyword, but it is marked as "not used".

Java的关键字列表指定跳转关键字,但它被标记为“未使用”。

This was probably done in case it were to be added to a later version of Java.

这可能是为了将其添加到更高版本的 Java 中。

If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

如果 goto 不在列表中,并且稍后将其添加到语言中,则使用单词 goto 作为标识符(变量名称、方法名称等)的现有代码将中断。但是因为 goto 是一个关键字,这样的代码现在甚至不会编译,并且在不破坏现有代码的情况下仍然可以让它在以后真正做一些事情。

回答by Daniel Cardoso

Java does not support goto, it is reserved as a keyword in case they wanted to add it to a later version

Java 不支持goto,它被保留为关键字,以防他们想将其添加到更高版本中

回答by Bill K

If you look up continue and break they accept a "Label". Experiment with that. Goto itself won't work.

如果您查找 continue 和 break,他们会接受“标签”。试验一下。Goto 本身不起作用。

public class BreakContinueWithLabel {

    public static void main(String args[]) {

        int[] numbers= new int[]{100,18,21,30};

        //Outer loop checks if number is multiple of 2
        OUTER:  //outer label
        for(int i = 0; i<numbers.length; i++){
            if(i % 2 == 0){
                System.out.println("Odd number: " + i +
                                   ", continue from OUTER label");
                continue OUTER;
            }

            INNER:
            for(int j = 0; j<numbers.length; j++){
                System.out.println("Even number: " + i +
                                   ", break  from INNER label");
                break INNER;
            }
        }      
    }
}

Read more

阅读更多

回答by Tirath

Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.

Java 也不使用行号,这是 GOTO 函数所必需的。与 C/C++ 不同,Java 没有 goto 语句,但 java 支持标签。标签在 Java 中唯一有用的地方是嵌套循环语句之前。我们可以使用 break 指定标签名称以中断特定的外部循环。

回答by Sohail Sankanur

There is not 'goto' in the Java world. The main reason was developers realized that complex codes which had goto would lead to making the code really pathetic and it would be almost impossible to enhance or maintain the code.

Java 世界中没有“goto”。主要原因是开发人员意识到必须转到的复杂代码会导致代码变得非常可悲,并且几乎不可能增强或维护代码。

However this code could be modified a little and using the concept of continue and break we could make the code work.

然而,这段代码可以稍微修改一下,使用 continue 和 break 的概念,我们可以使代码工作。

    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: while(true){
        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.");
            continue restart;
        }
        while(x<=factInput)
        {
            factValue*=x;
            x++;
        }
        System.out.println(factInput+"! = "+factValue);
        userInput.close();
        break restart;
}
    }
}

回答by Tatarize

gotois an unused reserved word in the language. So there is no goto. But, if you want absurdist theater you could coax one out of a language feature of labeling. But, rather than label a for loop which is sometimes useful you label a code block. You can, within that code block, call break on the label, spitting you to the end of the code block which is basically a goto, that only jumps forward in code.

goto是语言中未使用的保留字。所以没有goto。但是,如果你想要荒诞戏剧,你可以从标签的语言特征中哄骗一个。但是,不是标记有时有用的 for 循环,而是标记代码块。您可以在该代码块中,在标签上调用 break,将您吐到代码块的末尾,这基本上是一个 goto,它只会在代码中向前跳转。

    System.out.println("1");
    System.out.println("2");
    System.out.println("3");
    my_goto:
    {
        System.out.println("4");
        System.out.println("5");
        if (true) break my_goto;
        System.out.println("6");
    } //goto end location.
    System.out.println("7");
    System.out.println("8");

This will print 1, 2, 3, 4, 5, 7, 8. As the breaking the code block jumped to just after the code block. You can move the my_goto: {and if (true) break my_goto;and } //goto end location.statements. The important thing is just the break must be within the labeled code block.

这将打印 1, 2, 3, 4, 5, 7, 8。随着破解代码块跳转到代码块之后。您可以移动my_goto: {andif (true) break my_goto;} //goto end location.语句。重要的是中断必须在标记的代码块内。

This is even uglier than a real goto. Never actually do this.

这甚至比真正的转到更丑陋。永远不要这样做。

But, it is sometimes useful to use labels and break and it is actually useful to know that if you label the code block and not the loop when you break you jump forward. So if you break the code block from within the loop, you not only abort the loop but you jump over the code between the end of the loop and the codeblock.

但是,有时使用标签和中断很有用,知道如果在中断时标记代码块而不是循环,则向前跳实际上很有用。因此,如果您从循环内部中断代码块,您不仅会中止循环,还会跳过循环末尾和代码块之间的代码。