我正在做与处理异常相关的练习。在使用Scanner类和以下练习检查InputMismatchExceptions时,我从以下代码中获得了以下结果。
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.print("Enter an integer: ");
int a = getInt();
System.out.print("Enter a second integer: ");
int b = getInt();
int result = a + b;
System.out.println(result);
}
public static int getInt(){
while (true){
try {
return sc.nextInt();
}
catch(InputMismatchException e){
System.out.print("I'm sorry, that's not an integer."
+ " Please try again: ");
sc.next();
}
}
}
输出结果为:
Enter an integer: 2 3
Enter a second integer: 5
似乎如果第一次调用nextInt()我输入" 2 3"或两个整数之间有空格,下一次调用nextInt()时,它会收到第一个将两个整数相加,然后暂停程序。这里到底发生了什么?
P.S。有没有人有一些提示让我以更好的方式格式化我的代码并让其他编码人员更有条理地阅读?
答案 0 :(得分:1)
当您输入" 2 3" (两个整数之间有空格)scanner.nextInt()
将拉入2并使3仍然在扫描仪中。现在,当调用下一个nextInt()
时,它将拉入剩下的3,而用户不必再输入数据。
您可以使用nextLine()
解决此问题,并检查输入字符串是否包含空格。
这样的事情:
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
int a = getInt();
System.out.print("Enter a second integer: ");
int b = getInt();
int result = a + b;
System.out.println(result);
}
public static int getInt() {
while (true) {
try {
String input = sc.nextLine();
if (!input.contains(" ")) {
int integer = Integer.parseInt(input);
return integer;
} else {
throw new InputMismatchException();
}
} catch (InputMismatchException | NumberFormatException e) {
System.out.print("I'm sorry, that's not an integer. Please try again: ");
}
}
}
结果:
Enter an integer: 2 3
I'm sorry, that's not an integer. Please try again: 2
Enter a second integer: 3
5