【发布时间】:2016-04-26 12:24:32
【问题描述】:
我希望用户输入 80 到 120 之间的整数,没有字母和其他符号。这是我的代码:
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
//checking for integer input
while (!in.hasNextInt())
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
int userInput = in.nextInt();
//checking if it's within desired range
while (userInput<80 || userInput>120)
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
}
}
}
}
但是,我遇到了一个错误。有解决办法吗?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Array.main(Array.java:15)
谢谢! :)
编辑:谢谢汤姆,得到了解决方案,但想尝试不使用“do”
Scanner in = new Scanner(System.in);
int userInput;
do {
System.out.println("Please enter integers between 80 and 120.");
while (!in.hasNextInt())
{
System.out.println("That's not an integer!");
in.next();
}
userInput = in.nextInt();
} while (userInput<81 || userInput >121);
System.out.println("Thank you, you have entered: " + userInput);
}
}
【问题讨论】:
-
当然有!
catchjava.util.InputMismatchException并妥善处理。出于兴趣,您为什么要跳过输入? -
@Bathsheba 嗨,我想不使用 catch 来做这件事,因为我正在修改我的学校作业,这只是前几个主题(此时还没有学习 catch 异常)
-
将条件改为while (in.hasNextInt())