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

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

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按下时,这意味着用户想要退出测试,然后我中断了while loop并打印Test is

done,但是那样行不通,我知道原因可能是"break"中断了switch,我怎样才能让它打破while loop呢?

回答:

你可以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");

}

}

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

以上是 Java如何在switch语句下中断while循环? 的全部内容, 来源链接: utcz.com/qa/413295.html

回到顶部