私は基本的に、標準の入力ストリームからユーザー入力を読み取るメソッドから戻ろうとしています。ユーザーにはアプリケーションを終了するオプションがあるので、私はこの終了を行うための最良の方法を見つけようとしています。理想的には、私は戻って終了することができ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のメソッド内に応答することはありません。execute
CommandQuit
begin()
while(true)
begin()
main()
return;
execute
私の例で欠けているものはありますか?おそらく、何かが非常に明白であるため、現時点ではそれを見ることができません。助けてくれてありがとう。