Java How can I break a while loop under a switch statement?
Asked Answered
V

5

80

I have a homework to implement a simple testing application, below is my current code:

import java.util.*;

public class Test{

private static int typing;

public static void main(String argv[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("Testing starts");
    while(sc.hasNextInt()){
        typing = sc.nextInt();
        switch(typing){
            case 0:
              break; //Here I want to break the while loop
            case 1:
              System.out.println("You choosed 1");
              break;
            case 2:
              System.out.println("You choosed 2");
              break;
            default:
              System.out.println("No such choice");
        }
    }
      System.out.println("Test is done");
    }
}

What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?

Vitascope answered 2/4, 2014 at 21:24 Comment(0)
M
187

You can label your while loop, and break the labeled loop, which should be like this:

loop: while(sc.hasNextInt()){
    typing = sc.nextInt();
    switch(typing){
        case 0:
          break loop; 
        case 1:
          System.out.println("You choosed 1");
          break;
        case 2:
          System.out.println("You choosed 2");
          break;
        default:
          System.out.println("No such choice");
    }
}

And the label can be any word you want, for example "loop1".

Mutualize answered 2/4, 2014 at 21:26 Comment(4)
"loop" is a poor/boring choice of label. Funnier choices include "up", "out", "stuff", "theBank" and "dance".Amritsar
Jokes aside, giving the loop a slightly more informative label (in your case, perhaps scanner), allows the breaks to look like break scanner (stop scanner).Charleton
@Charleton that wasn't obvious, so thanks for pointing that out.Medorra
I don't understand the comments pointing to the label name; the answer is perfect! I had developing in Java for more than 7 years and this answer amazed me. Elegant, simple, and a perfect use of labels.Lucubrate
T
14

You need a boolean variable e.g. shouldBreak.

    boolean shouldBreak = false;
    switch(typing){
        case 0:
          shouldBreak = true;
          break; //Here I want to break the while loop
        case 1:
          System.out.println("You choosed 1");
          break;
        case 2:
          System.out.println("You choosed 2");
          break;
        default:
          System.out.println("No such choice");
    }
    if (shouldBreak) break;
Terefah answered 2/4, 2014 at 21:25 Comment(0)
H
5

Put the while inside a function and when you press 0 instead of break just return. For example :

    import java.util.*;

public class Test{

private static int typing;

public static void main(String argv[]){
    Scanner sc = new Scanner(System.in);
    func(sc);
      System.out.println("Test is done");
    }
}

public static void func(Scanner sc) {


    System.out.println("Testing starts");
    while(sc.hasNextInt()){
        typing = sc.nextInt();
        switch(typing){
            case 0:
              return; //Here I want to break the while loop
            case 1:
              System.out.println("You choosed 1");
              break;
            case 2:
              System.out.println("You choosed 2");
              break;
            default:
              System.out.println("No such choice");
        }
    }
}

}
Hallagan answered 2/4, 2014 at 21:40 Comment(0)
D
2

Here is a relatively simple way to do it!

Since you want to break the while loop if the value assigned to typing is 0, the easiest thing to do would be to check the value of typing, even before entering the switch-case statement.

import java.util.*;

public class Test{
    private static int typing;

    public static void main(String argv[]){
        Scanner sc = new Scanner(System.in);
        System.out.println("Testing starts");
    
        while(sc.hasNextInt()){
            typing = sc.nextInt();
        
            if (typing == 0){
                break;
            } 
        
            else{
                switch(typing){
                    case 1:
                        System.out.println("You chose 1");
                        break;
                    case 2:
                        System.out.println("You chose 2");
                        break;
                    default:
                        System.out.println("No such choice");
                }
            }
        }
        System.out.println("Test is done");
    }
}
Duchess answered 18/11, 2023 at 13:13 Comment(0)
D
1

How to terminate inner menu ?

Example Code :

import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); //used to get input
        int option1, option2 = 0;
        boolean loop_terminate = true; //flag used to terminate inner while loop

        //Main Menu
        while (true) {
            //Main Menu options
            System.out.println("1.Option 1");
            System.out.println("2.Option 2");
            System.out.println("3.Option 3");
            System.out.println("4.Option 4");
            System.out.println("5.Exit main menu");

            System.out.print("Please enter your choice : ");
            option1 = input.nextInt();

            switch (option1) {

                case 1:
                       //do something here    
                    break;
                case 2:
                       //do something here 
                    break;
                case 3:

                    while (loop_terminate) {
                        //Inner menu options
                        System.out.println("1.Inner Menu option 1");
                        System.out.println("2.Inner Menu option 2");
                        System.out.println("3.Inner Menu option 3");
                        System.out.println("4.Return to Main Menu");

                        System.out.print("Please enter your choice : ");
                        option2 = input.nextInt();
                        switch (option2) {

                            case 1:
                                break;
                            case 2:
                                break;
                            case 3:
                                break;
                            case 4:
                                loop_terminate = false; //this will terminate inner menu
                                break;
                            default:
                                System.out.println("Invalid option");
                                break;
                        }
                    }
                    break; //never forget to add this break statement
                case 4:
                      break;
                case 5:
                    return; //terminate outer menu

                default:
                    System.out.println("Invalid option");
            }
        }

    } 
}
Diction answered 9/12, 2017 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.