2015-11-20 81 views
-1

我有一個方法getIntInput(),它返回用戶調用時所做的選擇。所以現在我的問題是我怎麼能驗證用戶輸入是一定的選擇範圍說,像1,2,3,4,5只有少或更多的異常將拋出說無效選擇並返回到頂部再問。Java異常

我知道這可以用一段時間來實現,或者做到這一點,但我該如何去做。

public static int getIntInput(String prompt){ 
     Scanner input = new Scanner(System.in); 
     int choice = 0; 
     System.out.print(prompt); 
     System.out.flush(); 

      try{ 
       choice = input.nextInt(); 
      }catch(InputMismatchException e){ 
       System.out.print("Error only numeric are allowed"); 
       getIntInput(prompt); 
      } 

     return choice; 
    } 
+1

可能出現[在數字範圍內驗證掃描器輸入]的副本(http://stackoverflow.com/questions/30689791/validate-scanner-input-on-a-numeric-range) – cgmb

回答

0

如果值爲他們輸入不期望範圍內你也可以拋出一個異常。但是,只需使用do..while循環就可以處理告訴他們無效輸入並再次提示他們的要求。

正如你所建議的,使用do..while。添加if聲明來解釋爲什麼他們再次被提示。

public static int getIntInput(String prompt){ 
    Scanner input = new Scanner(System.in); 
    int choice = 0; 
    int min = 1; 
    int max = 5; 

    do { 
     System.out.print(prompt); 
     System.out.flush(); 

     try{ 
      choice = input.nextInt(); 
     }catch(InputMismatchException e){ 
      System.out.print("Error only numeric are allowed"); 
     } 
     if (choice < min || choice > max) { 
      System.out.println("Number must be between " + min + " and " + max); 
     } 
    } while (choice < min || choice > max); 

    return choice; 
} 

代替最小和最大硬編碼,您可以將它們作爲參數傳遞給getIntInput()

public static int getIntInput(String prompt, int min, int max){ 
    Scanner input = new Scanner(System.in); 
    int choice = 0; 

    ... 
}