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");
}
}
我现在要做的是当<$按c $ c> 0 ,表示用户想要退出测试,然后我打破 while循环
并打印测试已完成
,但它不能像那样工作,我知道原因可能是break
打破切换
,我如何让它打破 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?
推荐答案
你可以标签
你的while循环, break
标记为循环
,它应该是这样的:
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");
}
}
以及标签
可以是您想要的任何单词,例如loop1
。
And the label
can be any word you want, for example "loop1"
.
这篇关于Java如何在switch语句下打破while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!