【发布时间】:2014-04-08 05:56:31
【问题描述】:
我想检查两个整数输入是否在范围内且合法。以下代码是我想出的。
问题是当我检查第一个输入是否在范围内时,它不会弹出错误(不正确时),直到我输入第二个输入是否正确。当错误出现时,它只会打印错误以及等待用户输入的空行(没有明显原因);我在其中输入任何内容并点击“输入”,然后程序再次运行(继续循环),要求用户再次输入值,直到它正确为止。
输入字符时不会出现此问题。输入不匹配的错误非常有效。它打印错误,然后再次运行程序,要求用户再次输入值,直到它是合法的。
如何让它检查第一个输入以查看它是否在范围内,如果在用户点击输入后立即输出错误,然后检查第二个输入并执行相同操作?
这有意义吗?
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");
}
【问题讨论】:
-
你的意思是在 catch 块中?
-
OK 所以 user_input.nextLine();在 catch 块中,在弹出错误后停止随机空行。但我仍然想知道如何在每次输入后打印错误...
-
你要求第一个输入,然后,不检查它是否正确,你要求第二个输入。只有在那之后,您才检查这些值是否在范围内。您的程序正在按照您的要求执行。
标签: java variables exception error-handling integer