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

54 java break while-loop

我有一个功课来实现一个简单的测试应用程序,下面是我目前的代码:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在要做的是,当0按下时,表示用户想要退出测试,然后我打破while loop并打印Test is done,但它不能那样工作,我知道原因可能是"break"打破了switch,我怎么能让它打破while loop呢?

Zhe*_*Hao 127

你可以labelwhile循环,并breaklabeled 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

而且label可以是你想要的任何字,例如"loop1".

  • "循环"是一个糟糕/无聊的标签选择.Funnier的选择包括"up","out","stuff","theBank"和"dance". (29认同)
  • 除了笑话,给循环一个稍微提供信息的标签(在你的情况下,也许是`scanner`),让休息看起来像'破碎扫描仪'(停止扫描仪). (3认同)

pet*_*rov 11

你需要一个布尔变量,例如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;
Run Code Online (Sandbox Code Playgroud)


Sta*_*kos 5

将 while 放在函数中,当您按 0 而不是 break just 时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");
        }
    }
}

}
Run Code Online (Sandbox Code Playgroud)