Cómo usar correctamente la instrucción goto


Estoy tomando mi clase de informática AP de la escuela secundaria.

Decidí lanzar una declaración goto en uno de nuestros laboratorios solo para jugar, pero obtuve este error.

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)

Fui a una pregunta goto sobre Stackoverflow para averiguar cómo hacerlo correctamente, e hice exactamente como se demostró en una de las respuestas. Realmente no entiendo por qué el compilador quiere una declaración assert (al menos eso es lo que supongo que quiere), ni tengo idea de cómo usar assert. Parece para querer que la parte restart de goto restart; sea una variable, pero restart es solo una etiqueta que devuelve el programa a la línea 10 para que el usuario pueda ingresar un int válido. Si quiere que restart sea una variable, ¿cómo lo hago?

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();
    }
}
Author: StackFlowed, 2014-10-17

7 answers

Como ya se señaló en todas las respuestas goto - una palabra reservada en Java y no se usa en el idioma.

restart: se llama identificador seguido de dos puntos.

Aquí hay algunas cosas que debe tener en cuenta si desea lograr similar comportamiento -

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.
    }
}

No estoy seguro de si debo decir similar como ya tengo.

 59
Author: Tirath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-02 19:03:59

La lista de palabras clave de Java especifica la palabra clave goto, pero está marcada como "no utilizada".

Esto probablemente se hizo en caso de que se agregara a una versión posterior de Java.

Si goto no estuviera en la lista, y se agregara al lenguaje más adelante, el código existente que usa la palabra goto como identificador (nombre de variable, nombre de método, etc.) se rompería. Pero debido a que goto es una palabra clave, dicho código ni siquiera se compilará en el presente, y sigue siendo posible hacerlo en realidad hacer algo más tarde, sin romper el código existente.

 11
Author: Aditya Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-17 17:51:46

Si miras hacia arriba continuar y romper que aceptan una "Etiqueta". Experimenta con eso. Goto no funcionará.

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;
            }
        }      
    }
}

Leer más

 10
Author: Bill K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-25 07:14:03

Java no soporta goto, se reserva como palabra clave en caso de que quieran añadirla a una versión posterior

 3
Author: Daniel Cardoso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-17 17:55:00

goto no hace nada en Java.

 2
Author: Sizik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-17 17:50:39

Java tampoco usa números de línea, lo cual es una necesidad para una función GOTO. A diferencia de C / C++, Java no tiene la instrucción goto, pero java soporta label. El único lugar donde una etiqueta es útil en Java es justo antes de las instrucciones de bucle anidadas. Podemos especificar el nombre de la etiqueta con break para romper un bucle externo específico.

 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-16 04:51:39

No hay 'goto' en el mundo Java. La razón principal fue que los desarrolladores se dieron cuenta de que los códigos complejos que se habían ido conducirían a hacer el código realmente patético y sería casi imposible mejorar o mantener el código.

Sin embargo este código podría modificarse un poco y usando el concepto de continuar y romper podríamos hacer que el código funcione.

    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;
}
    }
}
 0
Author: Sohail Sankanur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-12 19:30:53