Java 无法从读取标准输入流的方法返回main()
我基本上是从一个从标准输入流读取用户输入的方法返回。因为用户可以选择退出应用程序,所以我正在尝试找出最好的方法。理想情况下,我将能够从Java 无法从读取标准输入流的方法返回main(),java,methods,return,command-pattern,control-flow,Java,Methods,Return,Command Pattern,Control Flow,我基本上是从一个从标准输入流读取用户输入的方法返回。因为用户可以选择退出应用程序,所以我正在尝试找出最好的方法。理想情况下,我将能够从begin()返回并让main()完成,从而退出应用程序 public static void main(String[] args) { begin(); } private static void begin(){ Machine aMachine = new Machine(); String select=nul
begin()
返回并让main()
完成,从而退出应用程序
public static void main(String[] args) {
begin();
}
private static void begin(){
Machine aMachine = new Machine();
String select=null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
try {
select = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your selection");
return;
}catch(Exception ex){
System.out.println("Error trying to evaluate your input");
return;
}
if (Pattern.matches("[RQrq1-6]", select)) {
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
}
else {
System.out.println(aMachine.badCommand()+select);
aMachine.getStatus();
}
}
}
当机器使用此方法执行用户给定的命令时,主逻辑发生:
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
同样,问题是一旦用户输入命令Q或Q,如何退出应用程序。quit命令如下所示:
public class CommandQuit implements Command {
public void execute(Machine aMachine) {
aMachine.getStatus();
return; //I would expect this to force begin() to exit and give control back to main()
}
}
现在,按照前面的建议,要退出应用程序,我尝试返回main(),基本上让main()完成。这样我就避免了使用任何System.exit(0)
,尽管那样也可以
因此,在这个例子中,我在CommandQuit
类的execute
方法中有一个return
语句,当我们从用户那里接收到一个Q或Q时调用该语句。但是,当begin()
执行退出命令时,控制流似乎从未响应返回,而不是从while(true)
循环返回,从begin()
,返回到main()
执行方法中的code>
我的例子中有没有遗漏什么?也许有些事情太明显了,我现在看不见。谢谢您的帮助。在execute()
中的return语句从execute()
返回,而不是begin()
。通常在这些情况下,CommandQuit.execute()
在a机器上设置一个标志,然后begin()
检查循环顶部的标志:
while (aMachine.stillRunning()) { // instead of while (true)
...
// This will clear aMachine.stillRunning() if the user quits.
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
}
execute()
中的return语句从execute()
返回,而不是从begin()
返回。通常在这些情况下,CommandQuit.execute()
在a机器上设置一个标志,然后begin()
检查循环顶部的标志:
while (aMachine.stillRunning()) { // instead of while (true)
...
// This will clear aMachine.stillRunning() if the user quits.
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
}
始终仅从当前函数返回(在本例中为CommandQuit.execute)。这与在函数结束后执行完全相同。您可以在机器中设置一个标志,使while循环一直运行到设置好为止,而不是永远运行:
在“机器”类中,您将有:
private boolean isRunning = false;
public boolean stillRunning() {
return isRunning;
}
public void stopRunning() {
isRunning = false;
}
您可以在aMachine.stillRunning()时循环并调用aMachine.stopRunning()来停止它
始终仅从当前函数返回(在本例中为CommandQuit.execute)。这与在函数结束后执行完全相同。您可以在机器中设置一个标志,使while循环一直运行到设置好为止,而不是永远运行:
在“机器”类中,您将有:
private boolean isRunning = false;
public boolean stillRunning() {
return isRunning;
}
public void stopRunning() {
isRunning = false;
}
您可以在aMachine.stillRunning()时循环并调用aMachine.stopRunning()来停止它