2015-11-20 54 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; 

    ... 
}