how do you restart game in java?
this is what i tried but did not work:
String playagain;
String y="y";
String n="n";
//there is a huge chunk of code that goes in here for the game
System.out.println("play another game?(y/n)");
playagain=input.next();
if(playagain==y){
Game.end();
Game.start();
}else if(playagain==n){
System.out.println("Goodbye");
}
game is the name of the class, but it insists i create a method for that to work. would anyone know an easier way to restart the game when player clicks y? Any help is appreciated
I suspect two things are happening in your original code:
You're using y
and n
, rather than "y"
and "n"
- the former would look like variable names to the compiler, whereas the latter are string literals, which I think we're after. If you're actually meaning the former, we'd need to declare some variables named y
and n
as Strings, give them some values (probably "y"
and "n"
respectively), although I don't think it's worth using variables in this case (given that they're only going to be referenced once in your code, no complex expressions, not mutable.
If you simply use == when comparing strings, Java will actually check whether the strings have the same reference (ie they're the exact same instance, the same object). If you're wanting to check the contents of the string, we need to evaluate string1.equals(string2)
, which will be true if they have the same content and false otherwise. Bit more information here.
EDIT: Okay, the problem is deeper than I first thought. Consider structuring your code like this instead of the above (if you don't have those start and end methods):
while (true) {
// Play the game here
// Play again?
boolean isPlayingAgain = true;
while (true) {
System.out.println("play another game?(y/n)");
String playingAgainResponse = input.next();
if (playingAgainResponse.equalsIgnoreCase("y")) {
break;
} else if (playingAgainResponse.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
isPlayingAgain = false;
break;
}
}
if (!isPlayingAgain) {
break;
}
}
So the outer loop only terminates if we player doesn't want to play again, otherwise we keep running the code to play the game. That inner loop ensures that the player enters either a "y" or a "n" (in upper or lower case, actually), and so it is handling the case where the player enters some gibberish.