2016-05-13 292 views
-1

我正在嘗試編寫一個程序,讓您在兩件事情中進行選擇。 但是在執行我選擇的選項後,我希望能夠返回相同選項的開頭。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

只要使用方法在任何開關或如果和循環在那裏。 – 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(); 
} 

如果您將自己的案例放入自己的方法中,則可以遞歸調用它們,直到您放入退出語句。遞歸工作,以及一個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; 
    } 
} 

您可以通過多種方式退出。這只是兩個答案。

+0

這正是我一直在尋找。謝謝! –

+0

不客氣。 – DarkJade

+0

遞歸是一個非常糟糕的主意,因爲這會導致一個'StackOverflowError'。這裏應該首先使用循環。 – Tom