-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;
}
可能出现[在数字范围内验证扫描器输入]的副本(http://stackoverflow.com/questions/30689791/validate-scanner-input-on-a-numeric-range) – cgmb