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

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".

Leave a Comment