Java 如何在 switch 语句下中断 while 循环? [英] Java How can I break a while loop under a switch statement?
问题描述
我有一个作业来实现一个简单的测试应用程序,以下是我当前的代码:
I have a homework to implement a simple testing application, below is my current code:
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循环
并打印测试完成
,但它不那样工作,我知道原因可能是"break"
打破了switch
,怎么能我让它打破 while 循环
代替?
What I want to do now is that when 0
is pressed, it means that the user wants to quit the test, then I break the while loop
and print Test is done
, but it doesn't work like that, I know the reason might be that the "break"
breaks the switch
, how can I let it break the while loop
instead?
推荐答案
你可以label
你的while循环,以及break
labeled loop
,应该是这样的:
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");
}
}
label
可以是任何你想要的词,例如 "loop1"
.
And the label
can be any word you want, for example "loop1"
.
这篇关于Java 如何在 switch 语句下中断 while 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!