使用
Scanner.hasNextInt():
Returns true if the next token in this scanner’s input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
这是一个例子:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
你不必解析或担心NumberFormatException。请注意,由于hasNextXXX方法不会超过任何输入,如果要跳过“垃圾”,则可能需要调用next(),如上所示。
相关问题