所以我有这样的代码:
protected void giveNr(Scanner sc) {
//variable to keep the input
int input = 0;
do {
System.out.println("Please give a number between: " + MIN + " and " + MAX);
//get the input
input = sc.nextInt();
} while(input < MIN || input > MAX);
}如果输入的内容不是整数,比如字母或字符串,程序就会崩溃,并给出错误InputMismatchException。我如何修复它,以便当输入了错误的输入类型时,再次要求人类输入(并且程序不会崩溃?)
发布于 2012-04-08 07:43:12
您可以捕获InputMismatchException,打印一条错误消息,告诉用户哪里出了问题,然后再次循环:
int input = 0;
do {
System.out.println("Please give a number between: " + MIN + " and " + MAX);
try {
input = sc.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That was not a number. Please try again.");
input = MIN - 1; // guarantee we go around the loop again
}
while (input < MIN || input > MAX)https://stackoverflow.com/questions/10059143
复制相似问题