Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Break in switch case

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

            }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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... 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading