我想检查两个整数输入是否在范围内且合法。以下代码是我提出的。
问题在于,当我检查第一个输入是否在范围内时,它不会弹出错误(不正确),直到我输入第二个输入是否正确。当错误出现时,它只会打印错误以及等待用户输入的空行(无明显原因);在其中输入任何内容并点击“输入”然后程序再次运行(继续循环),要求用户再次输入值,直到它正确为止。
输入字符时不会发生此问题。输入不匹配的错误非常有效。它打印错误,然后再次运行程序,要求用户再次输入值,直到它合法。
如何检查第一个输入以查看它是否在范围内并在用户点击输入后如果不正确则输出错误,然后检查第二个输入并执行相同操作?
这有意义吗?
public String totalTime(){
flag = 1;
do{
try{
System.out.print("Enter a starting destination: ");
int choice1 = user_input.nextInt();
System.out.print("Enter a final desination: ");
int choice2 = user_input.nextInt();
if( (choice1 >= 1 && choice1 <= 5) && (choice2 >= 1 && choice2 <= 5) ){
switch(choice1){
case 1: if (choice2 == 2){hour = 0; minutes = 10;} else if (choice2 == 3){hour = 0; minutes = 30;} else if (choice2 == 4) {hour = 1; minutes = 10;} else if (choice2 == 5) {hour = 1; minutes = 5;} break;
case 2: if (choice2 == 1){hour = 0; minutes = 10;} else if (choice2 == 3){hour = 0; minutes = 25;} else if (choice2 == 4) {hour = 1; minutes = 0;} else if (choice2 == 5) {hour = 0; minutes = 15;} break;
case 3: if (choice2 == 1){hour = 0; minutes = 48;} else if (choice2 == 2){hour = 0; minutes = 23;} else if (choice2 == 4) {hour = 0; minutes = 45;} else if (choice2 == 5) {hour = 0; minutes = 12;}break;
case 4: if (choice2 == 1){hour = 1; minutes = 5;} else if (choice2 == 2){hour = 1; minutes = 0;} else if (choice2 == 3) {hour = 0; minutes = 45;} else if (choice2 == 5) {hour = 0; minutes = 40;}break;
case 5: if (choice2 == 1){hour = 0; minutes = 30;} else if (choice2 == 2){hour = 0; minutes = 15;} else if (choice2 == 3) {hour = 0; minutes = 10;} else if (choice2 == 4) {hour = 0; minutes = 40;}break;
default: System.out.println("There is no such route");
}
flag = 2;
}
else if (choice1 < 1 || choice1 > 5 || choice2 < 1 || choice2 > 5){
throw new NumberFormatException("Integer is out of range.");
}
}
catch(NumberFormatException e){
System.out.println("The number is not between 1 and 5. Try again.");
System.out.println();
user_input.next(); //removes leftover stuff from input buffer
}
catch(InputMismatchException e){
System.out.println("This is not an integer. Try again.");
System.out.println();
user_input.next(); //removes leftover stuff from input buffer
}
}while (flag == 1);
return ("The total time is " + hour + " hours and " + minutes + " minutes");
}
答案 0 :(得分:0)
要验证并重新询问用户输入,您需要在while循环中请求输入,而不是离开循环直到输入有效。
因此,在要求第一个输入后,您可以立即执行类似
的操作System.out.println("Enter a starting destination: ");
int choice1 = user_input.nextInt();
while(choice1 < 1 || choice1 > 5) {
System.out.println("Invalid Input");
if(user_input.hasNextInt())
choice1 = user_input.nextInt();
else
user_input.next();
}
System.out.println("Enter a final desination: ");
int choice2 = user_input.nextInt();
while(choice2 < 1 || choice2 > 5 || choice2 == choice1) {
System.out.println("Invalid Input");
if(user_input.hasNextInt())
choice2 = user_input.nextInt();
else
user_input.next();
}
这种方式也避免了抛出仅用于控制程序流的不必要的错误(可能非常难以阅读)