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