Saturday, April 21, 2018

java - How to use goto statement correctly



I am taking my high school AP Computer Science class.



I decided to throw a goto 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(Factorial.java:28)


I went to a goto 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 assert statement (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?



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();

}
}

Answer



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
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 similar as I already have.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...