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循环,并break在labeled 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".
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)
将 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)
| 归档时间: |
|
| 查看次数: |
40285 次 |
| 最近记录: |