Java如何在switch语句下打断while循环?

我有一个function来实现一个简单的testing应用程序,下面是我目前的代码:

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

现在我想要做的是,当按下0时,意味着用户想要退出testing,然后打破while loop并打印Test is done ,但它不工作,我知道原因可能当"break"断开switch ,我怎么能让它打破while loop呢?

你可以label你的while循环,并break labeled loop ,应该是这样的:

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

label可以是任何你想要的单词,例如"loop1"

你需要一个布尔variables例如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; 

把一个function放在里面,当你按0而不是打破就return 。 例如 :

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