OK, so I'm sure this question has been beaten to death, but I still can't find the answer I need for my project.
I am working on building a casino game suite in java (I'm 110% sure that there are better, and easier languages for this, but I am learning java right now and I'd like to code in java for the practice.) My issue is that I cannot figure out how to structure my code. I am used to using goto statements (I started learning coding in small basic). For example:
import java.util.*;
public class CasinoGames
{
public static void main(String[] args)
{
Scanner keys = new Scanner(System.in);
sopln("Hello, and welcome to Casino Games!");
sopln("Would you like to login, register, or play as a guest?");
char token = keys.nextLine().toLowerCase().charAt(0);
randomlabelhere:
if (token == "l")
User.login();
else if (token == "r")
User.register();
else if (token == "g")
User.guestLogin();
else
sopln("Invalid Choice, please try again!");
goto somerandomlabel
I know this won't compile, so please don't mention that. I know that I can use a do-while loop for this, but if I wanted the option to do a goto, what alternatives do I have?
The closest thing Java has to a goto
are labels for break
and continue
. Goto has been considered harmful for longer than Java has been a language, and consequently Java doesn't have a goto implementation (and goto
is a reserved word so you cannot add one). Finally, since token
is a char
you should compare with char
literals like
while(true) {
if (token == 'l')
User.login();
else if (token == 'r')
User.register();
else if (token == 'g')
User.guestLogin();
else {
sopln("Invalid Choice, please try again!");
continue;
}
break;
}