在使用Scanner类的nextInt()方法时,如果抛出了InputMismatchException,我是否应该通过catch块来处理它?这是一个运行时异常,但由用户输入引起,而不是程序员的错误。
这是我的代码。
package com.sample.programs;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ScannerPractice {
public static void main(String[] args) {
readInteger();
}
private static void readInteger() {
// Created a Scanner object
Scanner input = new Scanner(System.in);
// Display a prompt text
System.out.println("Please enter an integer");
// Accept the input from user
int number;
try {
number = input.nextInt();
// Display the output to user
System.out.println("You entered: " + number);
} catch (InputMismatchException exception) {
System.err.println("You have entered wrong input. Please enter a number");
// Log the stack trace
readInteger();
} finally {
input.close();
}
}
}发布于 2016-04-23 08:31:35
不需要,您应该在调用nextInt()之前调用hasNextInt()。
这个异常实际上意味着程序员的错误,因为程序员在调用该方法之前忘记了检查有效性。
如果您想再次提示用户,请记住先丢弃错误的输入。
Scanner input = new Scanner(System.in);
int value;
for (;;) {
System.out.println("Enter number between 1 and 10:");
if (! input.hasNextInt()) {
System.out.println("** Not a number");
input.nextLine(); // discard bad input
continue; // prompt again
}
value = input.nextInt();
if (value < 1 || value > 10) {
System.out.println("** Number must be between 1 and 10");
input.nextLine(); // discard any bad input following number
continue; // prompt again
}
if (! input.nextLine().trim().isEmpty()) {
System.out.println("** Bad input found after number");
continue; // prompt again
}
break; // we got good value
}
// use value here
// don't close inputhttps://stackoverflow.com/questions/36805023
复制相似问题