【发布时间】:2010-12-16 17:25:03
【问题描述】:
我基本上是想从一个从标准输入流中读取用户输入的方法返回。由于用户可以选择退出应用程序,因此我正在尝试找出执行此操作的最佳方法exit。理想情况下,我将能够从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()
}
}
现在按照我之前的question 的建议,退出应用程序,我试图返回 main() 并基本上让 main() 完成。这样我就可以避免使用System.exit(0),尽管这样也可以。
所以,在这个例子中,我在CommandQuit 类的execute 方法中有一个return 语句,当我们收到来自用户的Q 或q 时调用它。但是,当begin() 执行退出命令时,而不是从while(true) 循环返回、退出begin() 并返回main(),控制流似乎永远不会响应@987654338 中的return; @CommandQuit 的方法。
我的示例中是否缺少任何内容?也许有些事情太明显了,以至于我现在看不到。感谢您的帮助。
【问题讨论】:
标签: java methods return command-pattern control-flow