在java中无法中断while循环
我无法打破while循环,请检查并向我推荐如何做在java中无法中断while循环,java,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 e
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
,以完全保留开关。之后,它将返回到while
语句,计算布尔退出
,并在为false时退出循环
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);
}
}
我在浏览器中编写代码,这样它仍然会有一些小错误。在while
循环中放入中断
。不在不相关方法的switch
语句中。实际上,你也需要一个break
。但它仍然与while
循环无关。实际上,您在哪里调用new Admin()
?不要继续在中重新创建您的系统。在开始时基于此创建一个扫描器,然后在整个程序中使用它。实际上,这是代码实际版本的简化代码,因为它太冗余了,但其想法是实现类似于此的嵌套while循环,它可以继续运行,直到满足条件为止。(在项目中,这些while循环一次又一次地欢迎用户访问门户,以便他能够进一步提供操作)编译、运行和再现问题的Post代码,a.我在代码前面加上import java.util.*;接口代码{static void main(String[]args){new Admin();}
它对我很有效。你确定吗,它在我的计算机中运行得很好。你在哪里调用new Admin()
?你是如何测试的?它实际上在第二个开关上没有中断语句的情况下也能工作。谢谢你,它实际上是在重新调用整个构造函数(因为它被放在另一个while循环中),我所要做的就是在我调用它的另一个类中放置一个break语句。