java - 如何忽略用户无效输入并重新提示相同的问题?
问题描述
当用户输入无效值时,如字符串或字符,程序应忽略它并再次显示上一个问题。到目前为止,我只能在捕获无效输入时让程序退出。
有效输入是int
和“q”,用户决定退出。
public static void partB() {
int score = 0;
int correct = 0;
int done = 0;
Scanner scan = new Scanner(System.in);
try {
while (true) {
int num1 = (int) (Math.random() * 20);
int num2 = (int) ((Math.random() * 20) + 1);
System.out.printf("%d %% %d = ?\n", num1, num2);
if (scan.hasNext("q")) break;
if (scan.nextInt() == (num1 % num2)) {
score += 20;
done += 1;
correct += 1;
System.out.println("Correct answer,current score :" + score
+ ",performance: "
+ correct + "/" + done);
} else {
done += 1;
System.out.println("Incorrect answer, Current score:" +
score
+ ", performance: " + correct + "/" + done);
}
}
} catch (InputMismatchException e) {
System.out.println("invalid input"); //but this terminate program
}
System.out.println("Finish");
}
代码应该像这样运行:
18 % 12 = ?
6
Correct answer, Current score: 20, performance: 1/1
14 % 16 = ?
a
Invalid input
14 % 16 = ?
14
Correct answer, Current score: 40, performance: 2/2
20 % 4 = ?
q
Finish.
解决方案
您需要移动块try-catch
内部while
。此外,当有 a 时,InputMismatchException
您必须完成阅读该行(因为您使用Scanner#nextInt
而不是Scanner#nextLine
)并将变量 ( repeatValue
) 设置为true
。使用此变量,您可以决定是否需要生成新值或使用以前的值。
看到它在这里运行:
public static void main(String[] args) {
int score = 0;
int correct = 0;
int done = 0;
Scanner scan = new Scanner(System.in);
boolean repeatValue = false;
int num1 = 0; // put values outside while in order to re-use them when we need to repeat the same question
int num2 = 0;
while (true) {
try {
// if the user input was incorrect (repeatValue = true), use old the previous values for num1 and num2
num1 = repeatValue ? num1 : (int) (Math.random() * 20);
num2 = repeatValue ? num2 : (int) ((Math.random() * 20) + 1);
System.out.printf("%d %% %d = ?\n", num1, num2);
repeatValue = false; // restore flag state
if (scan.hasNext("q"))
break;
if (scan.nextInt() == (num1 % num2)) {
score += 20;
done += 1;
correct += 1;
System.out.println(
"Correct answer,current score :" + score + ",performance: " + correct + "/" + done);
} else {
done += 1;
System.out.println(
"Incorrect answer, Current score:" + score + ", performance: " + correct + "/" + done);
}
} catch (InputMismatchException e) {
System.out.println("invalid input");
scan.next();
repeatValue = true; // flag set to use the same values as before
}
}
System.out.println("Finish");
}
推荐阅读
- python - Flask-Login logout_user 不改变 is_authenticated
- php - Laravel 查询绑定和取消绑定
- javascript - Google+“链接无效”错误添加到任何社交共享
- mysql - 如何更新 MySql 中的数百万条记录?
- java - java中的可选参数(可以为null)
- python - 如何交换列表中的两个字节并最终将其打印为 int?
- php - 如何在没有标准身份验证的情况下使用 laravel RegisterController (php artisan make:Auth)
- c# - 为什么字符串不能转换为日期时间?
- javascript - Javascript - 如何验证类构造函数的参数是否存在
- usb - /sys/bus/usb/ 在所有 Linux 发行版中具有相同的结构