2013-02-01 96 views
0

這裏是菜單類Java獲取整數輸入法需要輸入兩次

import java.util.Scanner;

公衆課程菜單{String} [] menu_options;

public Menu(String[] menu_options) { 
    this.menu_options = menu_options; 
} 

public int getUserInput() { 
    int i = 1; 
    for (String s : this.menu_options) { 
     System.out.println(i + ". " + s); 
     i++; 
    } 

    int selection = getint_input(menu_options.length); 
    return (selection); 
} 

private int getint_input(int max) { 
    boolean run = true; 
    int selection = 0; 

    while (run) { 
     System.out.print("Select an option: "); 
     Scanner in = new Scanner(System.in); 


     if (in.hasNextInt()) { 
      int value = in.nextInt(); 
      if(value>=1 || value<=max){ 
       selection = value; //fixed this now working 
       run = false;  
      } 

     } else { 
      System.out 
        .print("Invalid input. Please enter a integer between 1 and " 
          + max + ": "); 

     } 
    } 
    return selection; 
} 

}

這裏是menudriver我使用

公共類Menutester {

public static void main(String[] args) { 
    String[] menuitems = new String[2]; 
    menuitems[0] = "option one"; 
    menuitems[1] = "option two"; 
    Menu tm = new Menu(menuitems); 
    int choice = tm.getUserInput(); 
    System.out.println("Got input"); 
} 

}

我第一次輸入的東西它不到風度regester在所有和當我嘗試調試它在日食它給我錯誤FileNotFou ndException(Throwable)。(String)第一個輸入的行:195。

這是它返回

  1. 選擇一個
  2. 方案二 選擇一個選項:1(我進入了這一點,並按下回車) 1(同樣在這裏只是它regestered輸入) 了輸入

回答

4

nextInt讀取輸入並將其從緩衝區中移除。如果不存儲該值,則無法調用它。

調用一次,存儲值,然後做所有需要的檢查。

更改此:

if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) { 
      selection = in.nextInt(); 
//... 

此:

if(in.hasNextInt()) { 
    int selection = in.nextInt(); 
    if(selection >= 1 || selection <= max) { 
     run = false; 
    } 
} 
+0

好吧,我確實解決了這個問題並更新了我的代碼。感謝您的幫助,但它仍然需要兩個輸入,當我運行它。它是這樣運行的,我改變了驅動程序打印出來的值一旦得到它
1.選項一 2.選項二
選擇一個選項:1(我的輸入,沒有發生)
1(我的輸入)
1(電腦打印出我的選擇現在)
對不起,即時格式化此評論時出現問題 – user1896670

+2

你仍然調用'nextInt'兩次,所以......兩個輸入。 –

+1

使用更好的版本編輯了固定代碼。第二次承認甚至不需要。 –

1

取代:

if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) { 
     selection = in.nextInt(); 
     run = false; 
     System.out.println(run); 

    } 

爲:

int input = in.nextInt(); 
if (input >= 1 || input <= max) { 
    selection = in.nextInt(); 
    run = false; 
    System.out.println(run); 
} 

並再試一次。

+0

這仍然是錯誤的。你正在調用'nextInt'兩次。 –