Johnny Coder Johnny Coder - 1 year ago 226
Java Question

How to use goto statement correctly

I am taking my high school AP Computer Science class.

I decided to throw a

statement into a one of our labs just to play around, but I got this 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(

I went to a
question 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
statement (at least that's what I assume it wants), nor do I have any idea how to use
. 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
. If it wants restart to be a variable, how do I do that?

import java.util.*;

public class Factorial
public static void main(String[] args)
int x = 1;
int factValue = 1;
Scanner userInput = new Scanner(;
System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
int factInput = userInput.nextInt();

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;
System.out.println(factInput+"! = "+factValue);

Answer Source

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

restart: is called an identifier followed by a colon.

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

outer:                   should be placed exactly before the loop
loopingConstructOne  {   we can have statements before the outer but not inbetween the label and the loop          
    loopingConstructTwo {
        continue;       //goes to the top of loopingConstructTwo and continue
        break;          //breaks out of loopingConstructTwo
        continue outer; //goes to the outer label and reenters loopingConstructOne
        break outer;    //breaks out of the loopingConstructOne
        continue inner; //this will behave similar to continue

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download