我需要编写一个程序,可以验证用户输入为整数,并防止它崩溃时,使用的输入不是整数。所以我在这里使用try和catch。然而,当用户输入是非整数时,我得到了一个无限循环。下面是我的代码
do {
try {
a = sc.nextInt();
} catch (InputMismatchExpression e) {
System.out.println("This is not integer");
}
} while(a < 1 || a > 10);发布于 2020-05-08 10:15:47
一旦扫描程序抛出异常,现有值将保持“未消耗”。为了避免这种情况,您需要添加sc.next()行来使用现有的输入,并使Scanner等待用户的下一个值。
do {
try {
a = sc.nextInt();
} catch (InputMismatchExpression e) {
sc.next(); // this "consumes" the invalid input and throws away
System.out.println("This is not integer");
}
} while(a < 1 || a > 10);发布于 2020-05-08 10:04:11
如果您实际上想中断循环,如果用户输入是一个非整数,那么您可以简单地在代码中添加一个标志值:
int flag = 0;
do {
try {
a = sc.nextInt();
} catch (InputMismatchExpression e) {
System.out.println("This is not integer");
flag=1;
}
} while((a < 1 || a > 10)&&flag==0);如果是flag=1,循环就会中断。
发布于 2020-05-08 10:08:30
正常使用regex检查用户输入如下:
String userInput = "1234567";
boolean isNumber = userInput.matches("^\\d+$");
System.out.println(isNumber);https://stackoverflow.com/questions/61676354
复制相似问题