2013-05-03 57 views
-1

這裏是我的World.java計劃留在循環

while (option == 1) 
    { 
     a.generate(); 
     a.count(); 
     System.out.println("Max number is "+ a.maximum(max)); 
     System.out.println("Average number is "+ a.average(aver)); 
     System.out.println("Min number is "+ a.minimum(min)); 
     System.out.println("Do you want to run it again (y/n)?: "); 
     a.getchoice(); 
    } 
    if (option == 2) 
    { 
     System.out.println("Program exits."); 
     System.exit(0); 
    } 

的代碼,這裏是我rg.java代碼

public int getchoice() { 
      Scanner reader = new Scanner(System.in); 
      String selection = reader.nextLine(); 
      if(!selection.toLowerCase().equals("y") && !selection.toLowerCase().equals("n")) 
      { 
       System.out.print("Invalid. Please enter 「y」 or 「n」: "); 
       return this.getchoice(); 
      } 
      if (selection.toLowerCase().equals("y")){ 
       return 1; 
      } 
      else 
      { 
       return 2; 
      } 

我想回到變量運行選項y/n在世界級。

但問題是,如果我按y鍵運行程序後,再出事了,無論是我按y或n程序仍在執行,就好像選擇是1

可有人檢查,找出哪一部分在我的代碼中被冤枉了?對不起,這個newb代碼,因爲我剛開始學習java

回答

2

你不明白你的方法getChoice()的結果變量option。所以while循環將永遠不會終止。

更改爲

while (option == 1) 
{ 
    a.generate(); 
    a.count(); 
    System.out.println("Max number is "+ a.maximum(max)); 
    System.out.println("Average number is "+ a.average(aver)); 
    System.out.println("Min number is "+ a.minimum(min)); 
    System.out.println("Do you want to run it again (y/n)?: "); 
    option = a.getchoice(); 
} 
3

你從來沒有設置option

試試這個:

option = a.getChoice();