我基本上是在尝试从一个从标准输入流中读取用户输入的方法返回。由于用户可以选择退出应用程序,因此我正在尝试找出执行此退出的最佳方法。理想情况下,我将能够返回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
在用户使用此方法执行给定命令时:
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
同样,问题是如何在用户输入命令 Q 或 q 后退出应用程序。退出命令是这样的:
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)
,尽管那也很好。
所以,在这个例子中,我在类的方法中有一个return
语句,当我们收到一个 Q 或来自用户的 q 时调用它。但是,当执行退出命令时,控制流似乎永远不会响应CommandQuit 方法的内部,而不是从循环中返回、退出和返回。execute
CommandQuit
begin()
while(true)
begin()
main()
return;
execute
我的示例中是否缺少任何内容?也许有些事情太明显了,以至于我现在看不到。谢谢你的帮助。