-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