举个例子,以下的代码,它会一直在while里面循环,但我们想在输入4的时候,退出循环。
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println(“Menu”);
System.out.println(“1:buy”);
System.out.println(“2:see”);
System.out.println(“3:seek”);
System.out.println(“4:exit”);
int option = sc.nextInt();
switch (option) {
case 1:
System.out.println(“welcome to buy”);
break;
case 2:
System.out.println(“welcome to see”);
break;
case 3:
System.out.println(“welcome to seek”);
break;
case 4:
break ;
default:
System.out.println(“get out”);
}
这时我们只要在while前面加上o:,然后选择我们需要触发之后才能语句,如case 4 ,将break;改成break o;这时就可以实现特定条件跳出死循环。
如何触发某个条件,跳出while(true)这个死循环?
最新推荐文章于 2024-09-20 19:08:23 发布