2015-10-31 24 views
2

我有一個程序,它應該顯示一個菜單從用戶選擇一個數字從菜單中選擇做它應該做的,然後返回到菜單,我不知道如何返回到菜單?如何返回程序的某些部分? java

這裏是我的代碼:

public class tst { 
    public static void main (String [] args){ 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Select"); 
     int slct = reader.nextInt(); 
     System.out.println("1.optionone"); 
     System.out.println("2.optiontwo"); 
     System.out.println("1.optionthree"); 
     switch (slct){ 
      case 1:System.out.println("you have selected optionone");// and then its suposed to go back to the menu 
      case 2:System.out.println("you have selected optiontwo");// and then its suposed to go back to the menu 
      case 3:System.out.println("you have selected optionthree");// and then its suposed to go back to the menu 
     }   
    }   
} 

問題的我怎樣才能使所以打印已選定後x選項我返回菜單一遍嗎?

回答

3

使用while循環。這可以讓你在到達結尾後循環回到循環的開始。

編輯:Java沒有goto聲明。但是,如果您決定學習一種新語言(如C)確實goto,請不要使用它。

不管你做什麼,使用goto。這是goto被認爲是非常不好的做法,並已受到absurd humor

實施例:

boolean keepGoing = true; 
while (keepGoing){ 
    //print out the options 
    int slct = reader.nextInt(); //get input 
    switch(slct){ 
     case 1: 
      //user inputted 1 
      break; //otherwise you will fall through to the other cases 
     case 2: 
      //... 
      break; 
     case 3: 
      //... 
      break; 
     case 4: //or other number to quit, otherwise this will repeat forever 
      keepGoing = false; //stop the loop from repeating again 
      break; 
    } 
} 
+0

謝謝它真的幫助我! –

+3

除Java不允許使用'goto'外。像[xkcd](http://www.xkcd.com/292/)一樣可愛,在Java中使用'goto'並不錯,這是一個編譯錯誤。 – Linus

1

在你的情況下,你可以使用do while循環來設計你的菜單。你可以重新設計你的菜單看起來像:

int slct = 0; 

do { 
    System.out.println("1.optionone"); 
    System.out.println("2.optiontwo"); 
    System.out.println("3.optionthree"); 
    System.out.println("4.Quit"); 
    Scanner reader = new Scanner(System.in); 
    System.out.println("Select"); 
    slct = reader.nextInt(); //get input 

    switch(slct){ 
    case 1: 
    //user inputted 1 
    break; //otherwise you will fall through to the other cases 
    case 2: 
    //... 
    break; 
    case 3: 
    //... 
    break; 
    } 


} while(slct != 4); 

當用戶輸入4選項,那麼它會打破循環。意思是while循環會使用4個輸入中斷。

+0

?我不明白你的答案我不需要退出選項我需要它的後,我選擇了一個選項和聲明與該選項相關聯它執行它返回到菜單 –

+0

@JuanAlvarez我希望現在它清楚。 –

+0

現在我確實得到你想說的 –