2013-06-05 30 views
1

我正在創建一個簡單的程序,使用java語言,它使用一堆類似的方法從用戶檢索信息。我用來處理用戶輸入無效數據的方法對我來說似乎非常不正確,因此我正在尋求有關如何更好地處理無效數據的專業指導。Java:更容易的方式來重新提示用戶輸入無效數據時輸入

我試圖搜索類似的問題,但沒有找到。

這是我的方法之一的樣本:

public static int getInput() 
{ 
    int temp = 1; 

    do 
    { 
     System.out.println("Answers must be between 1 and 15"); 
     temp = reader.nextInt(); 

     if(temp >=1 && temp <= 15) 
     { 
      return temp; 
     } 
     else 
     { 
      System.out.println("Please enter a valid value"); 
     } 
    }while(temp > 15 || temp < 1); 

    //This value will never be reached because the do while loop structure will not end until a valid return value is determined 
    return 1; 
}//End of getInput method 

有沒有更好的方式來寫這個方法?

這個問題是完全組成的,所以我可以學習一個更好的方法來實現我的未來計劃。

正在使用帶標籤的break語句是否可以接受?如:

public static int getInput() 
{ 
    int temp = 1; 

    start: 

     System.out.println("Answers must be between 1 and 15"); 
     temp = reader.nextInt(); 

     if(temp >=1 && temp <= 15) 
     { 
      return temp; 
     } 
     else 
     { 
      System.out.println("Please enter a valid value"); 
      break start; 
     } 


} 

非常感謝您提前。

+0

看起來不錯。順便說一句,爲什麼你不使用GUI? AWT/SWT /擺動....?在那種情況下,你有很多選擇。一個是InputVerifier - http://stackoverflow.com/questions/12997742/java-swing-implementing-a-validy-check-of-input-values – Jayan

+0

@Jayan我只是想學習一個新的概念;不需要GUI來說明問題。必須有更好的方法來做到這一點,最後的返回語句永遠不會到達,並且檢查temp是否在兩次允許的值內。編輯:對不起,我沒有注意到最後一句;我想在沒有GUI的情況下做到這一點。 – Singh

回答

2

你忘了檢查的情況下,所輸入的非數值(Scanner#nextInt拋出一個java.util.InputMismatchException)。一個照顧這個問題的建議,不那麼多餘,也更靈活:

public static int getInput(int min, int max) { 
    for (;;) { 
     Scanner scanner = new Scanner(System.in); 
     System.out.println(String.format("Answers must be between %s and %s", min, max)); 
     try { 
      int value = scanner.nextInt(); 
      if (min <= value && value <= max) { 
       return value; 
      } else { 
       System.out.println("Please enter a valid value"); 
      } 
     } catch (InputMismatchException e) { 
      System.out.println("Input was no number"); 
     } 
    } 
} 
+0

感謝您的回答。我喜歡使用「for(;;){}」我不知道這是可能的。 :) – Singh

+0

我有一個問題;當InputMismatchException被捕獲時,「input is no number」消息被無限打印出來......我如何防止這種情況發生? – Singh

+0

奇怪的是,我工作正常,只是檢查。確保實例化循環內的Scanner *。 – qqilihq

0

如果你只是擔心回報不使用,雙重檢查溫度,你可以這樣做

public static int getInput() 
{ 
    while(true) 
    { 
     System.out.println("Answers must be between 1 and 15"); 
     temp = reader.nextInt(); 

     if(temp >=1 && temp <= 15) 
     { 
      return temp; 
     } 
     else 
     { 
      System.out.println("Please enter a valid value"); 
     } 
    } 
}//End of getInput method 
+0

感謝您的協助:) – Singh

相關問題