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を入力した後、アプリケーションを終了する方法です。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)、それでも問題ありません。

したがって、この例では、ユーザーからQまたはqを受け取ったときに呼び出されるクラスのメソッドにreturnステートメントがあります。ただし、quitコマンドを実行すると、ループから戻ったり、から戻ったり、戻ったりする代わりに、制御フローがCommandQuitのメソッド内に応答することはありません。executeCommandQuitbegin()while(true)begin()main()return;execute

私の例で欠けているものはありますか?おそらく、何かが非常に明白であるため、現時点ではそれを見ることができません。助けてくれてありがとう。

4

2 に答える 2

4

のreturnステートメントは、ではなく、execute()から戻ります。通常、これらの場合、にフラグを設定してから、ループの先頭でフラグをチェックします。execute()begin()CommandQuit.execute()aMachinebegin()

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;
    }

そして、aMachine.stillRunning()中にループし、aMachine.stopRunning()を呼び出して停止します。

于 2009-11-15T03:27:11.283 に答える