2016-05-13 12 views
-1

私はあなたが2つのことを選ぶことができるプログラムを書こうとしています。 しかし、私が選択したオプションを実行した後、同じオプションの先頭を返すことができるようにしたい。SwitchまたはIfステートメント

switch (option) { 
case 1: 
    System.out.println("Start of option 1"); 
    //option 1 will do things here 
    System.out.println("End of option 1"); 
    //I want to return at the beginning of this case at the end of it 
    break; 

case 2: 
    System.out.println("Start of option 2"); 
    //option 2 will do things here 
    System.out.println("End of option 2"); 
    //I want to return at the beginning of this case at the end of it 
    break; 

default: 
    break; 
} 

選択したケースから抜け出すオプションもあります。 また、代わりにif文を使ってやろうとしていることを実装する方が簡単でしょうか?

+1

スイッチまたはifとloopのどちらかでメソッドを使用するだけです。 – Tom

+0

あなたはループが必要なのですか? –

答えて

0
case 2: 
    case2sub(); 
default: 
    break; 
} 
} 

public static void case2sub() { 
    System.out.println("Start of option 2"); 
    //option 2 will do things here 
    System.out.println("End of option 2"); 
    //I want to return at the beginning of this case at the end of it 
    boolean end = false; 
    System.out.println("QUIT? (Y/N)"); 
    keyboardInput = new Scanner(System.in).nextLine(); 
    if (keyboardInput.equalsIgnoreCase("Y")) 
      end = true; 
    else{} 
    if (end){} 
    else 
     case2sub(); 
} 

ケースを独自の方法で配置する場合は、exitステートメントを入れるまで再帰的に呼び出すことができます。再帰は機能し、whileループも同様です。

public static void case2sub() { 
    boolean end = false; 
    while (!end) 
    { 
    end = false; 
    System.out.println("Start of option 2"); 
    //option 2 will do things here 
    System.out.println("End of option 2"); 
    //I want to return at the beginning of this case at the end of it 
    System.out.println("QUIT? (Y/N)"); 
    keyboardInput = new Scanner(System.in).nextLine(); 
    if (keyboardInput.equalsIgnoreCase("Y")) 
     end = true; 
    } 
} 

この方法をいくつでも終了できます。これらはちょうど2つの答えです。

+0

これはまさに私が探していたものです。ありがとうございました! –

+0

ようこそ。 – DarkJade

+0

再帰は非常に悪い考えです。これは 'StackOverflowError'を引き起こす可能性があるためです。ループを使用するのが望ましいでしょう。 – Tom

関連する問題