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

2022-08-31 13:36:12

我有一个家庭作业来实现一个简单的测试应用程序,下面是我当前的代码:

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

我现在想做的是,当被按下时,这意味着用户想要退出测试,然后我打破并打印,但它不是那样工作的,我知道原因可能是打破的,我怎么能让它打破代替?0while loopTest is done"break"switchwhile loop


答案 1

你可以同时循环,和 ,它应该是这样的:labelbreaklabeled 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"


答案 2

您需要一个布尔变量,例如 .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;