我有一个家庭作业来实现一个简单的测试应用程序,下面是我的当前代码:
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呢?
发布于 2014-04-02 21:26:06
您可以label自己的while循环,并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");
}
}label可以是您想要的任何单词,例如"loop1"。
发布于 2014-04-02 21:25:13
您需要一个布尔变量,例如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;发布于 2014-04-02 21:40:06
将时间放在函数中,当您按0而不是换行时,只需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");
}
}
}
}https://stackoverflow.com/questions/22823395
复制相似问题