I’m coding a little tic tac toe game in java and I’m adding a functionnnality that asking if the player wants to continue to play or not. The problem is that in my switch, the break is not understood and don’t break the program when we say that we want to stop. Can someone help me find the problem in my code ? Thanks !
System.out.println("Do you want to continue ? (yes/no) ?"); String playAgain = scanner.nextLine(); switch (playAgain) { case "yes": System.out.println("let's continue"); case "no": System.out.println("Bye"); break; default: System.out.println("Please enter a right instruction"); }
Advertisement
Answer
That is not the way the break
keyword works. It ends the switch
statement, not the program.
In your code, if the option is yes
, both yes
and no
codes will be executed because there is no break
before the no
.
You probably want something like that:
System.out.println("Do you want to continue ? (yes/no) ?"); String playAgain = scanner.nextLine(); switch (playAgain) { case "yes": System.out.println("let's continue"); break; case "no": System.out.println("Bye"); System.exit(); default: System.out.println("Please enter a right instruction"); // You will need some control loop to make it work... }