Java异常
我有一个方法Java异常,java,exception,methods,Java,Exception,Methods,我有一个方法getIntInput(),它返回用户在调用时所做的选择。所以现在我的问题是,我如何验证用户输入是否在一定的选项范围内,比如1,2,3,4,5,只有小于或大于此范围的内容才会抛出异常,比如无效选择,然后返回顶部再次询问 我知道这可以用一段时间或做一段时间来实现,但我将如何去做呢 如果他们输入的值不在所需范围内,则可能引发异常。然而,简单地使用do..while循环将处理告诉他们无效输入并再次提示他们的需求 正如你所建议的,使用do..while。添加if语句,解释再次提示的原因 pu
getIntInput()
,它返回用户在调用时所做的选择。所以现在我的问题是,我如何验证用户输入是否在一定的选项范围内,比如1,2,3,4,5,只有小于或大于此范围的内容才会抛出异常,比如无效选择,然后返回顶部再次询问
我知道这可以用一段时间或做一段时间来实现,但我将如何去做呢
如果他们输入的值不在所需范围内,则可能引发异常。然而,简单地使用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;
}
可能重复的
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;
}
public static int getIntInput(String prompt, int min, int max){
Scanner input = new Scanner(System.in);
int choice = 0;
...
}