0

我基本上是在尝试从一个从标准输入流中读取用户输入的方法返回。由于用户可以选择退出应用程序,因此我正在尝试找出执行此退出的最佳方法。理想情况下,我将能够返回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 方法的内部,而不是从循环中返回、退出和返回。executeCommandQuitbegin()while(true)begin()main()return;execute

我的示例中是否缺少任何内容?也许有些事情太明显了,以至于我现在看不到。谢谢你的帮助。

4

2 回答 2

4

execute()return from中的 return 语句execute(), not begin()。通常在这些情况下,CommandQuit.execute()设置一个标志 on aMachine,然后begin()检查循环顶部的标志:

while (aMachine.stillRunning()) {  // instead of while (true)
    ...
    // This will clear aMachine.stillRunning() if the user quits.
    aMachine.getCommand(select.toUpperCase()).execute(aMachine);
}
于 2009-11-15T03:23:14.523 回答
0
return;

始终仅从当前函数返回(在本例中为 CommandQuit.execute)。这与在函数结束后执行完全相同。您可以在 aMachine 中设置一个标志,并使 while 循环运行直到它被设置,而不是永远运行:

在“机器”类中,您将拥有:

    private boolean isRunning = false;
    public boolean stillRunning() {
        return isRunning;
    }
    public void stopRunning() {
        isRunning = false;
    }

你会循环 while aMachine.stillRunning() 并调用 aMachine.stopRunning() 来停止它。

于 2009-11-15T03:27:11.283 回答