[英]Cannot break out of while loop in java
我无法跳出 while 循环,请查看并推荐我怎么做
public class Admin {
boolean exit=false;
public Admin(){
while (!exit){
printInstructions();
}
}
public void printInstructions(){
System.out.println("check 1 to print hi");
System.out.println("check 2 to exit");
Scanner scanner=new Scanner(System.in);
int choice=scanner.nextInt();
scanner.nextLine();
choose(choice);
}
public void choose(int choice){
switch(choice){
case 1:
System.out.println("hi");
break;
case 2:
exit=true;
break;
}
}
}
我希望代码停止执行,但相反它运行了很多次。 但是while循环一遍又一遍地运行。 我想知道为什么?
在两个switch
语句中添加break
或return
以完全离开 switch。 之后它将返回while
语句,评估boolean exit
并在为false
时退出loop
。
public void choose(int choice){
switch(choice){
case 1:
System.out.println("hi");
break;
case 2:
exit=true;
break;
}
}
您可以尝试将代码分解为更小的方法/函数。 但是如果您的功能相互交互会更好。 为了使您的函数成为可能,作为执行的结果,您的函数必须返回一些值:
// returns exit flag
public bool choose(int choice){
switch(choice){
case 1:
System.out.println("hi");
return false;
case 2:
return true;
}
}
// print instructions and return the choose
public int printInstructions(){
System.out.println("check 1 to print hi");
System.out.println("check 2 to exit");
Scanner scanner=new Scanner(System.in);
int choice=scanner.nextInt();
scanner.nextLine();
return choice;
}
public Admin(){
while (!exit){
int result = printInstructions();
exit = choose(result);
}
}
我在浏览器中编写代码,所以它仍然可能有一些小错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.