如何解决该程序仍会抛出InputMismatchException并退出,即使已被捕获
我只是在学习Java,并且正在努力处理异常。我正在尝试编写一个快速程序,该程序接受一些输入并将它们转换为不同的单位。
我正在使用Scanner接收输入,并且试图防止InputMisatchException,但是尽管在它周围放置了try-catch块来处理异常,但它仍然存在。代码是波纹管的。希望能对您有所帮助!预先感谢。
import java.util.InputMismatchException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
//init variables
String name = "";
int age = -1;
int height_in_cm = -1;
//Init Scanner
Scanner input = new Scanner(system.in);
//Get the input from the user and save to the initiated variables above.
System.out.print("Please enter your name: ");
name = input.nextLine();
try{
System.out.printf("hey,%s. How old are you?: ",name);
age = input.nextInt();
} catch (InputMismatchException e){
System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ",name);
age = input.nextInt();
}
System.out.print("And finally,what is your height in CM?: ");
height_in_cm = input.nextInt();
//close the scanner to protect from resource leaks.
input.close();
}
}```
解决方法
您还需要尝试一下
height_in_cm = input.nextInt();
否则,您将获得另一个例外!
,发生异常的原因是,当第一次引发异常时,扫描程序(输入)不会更新其指针,因此catch块中的input.nextInt()
会读取与{{1 }}。
要解决此问题,请在读取int值之前在catch块中添加input.nextInt()
。
input.nextLine()
,
原因是您在catch块中捕获了错误。尝试为其实现一个循环。还请记住使用input.next();
清除缓冲区,否则您将遇到无限循环
do
{
try
{
System.out.printf("Hey,%s. How old are you?: ",name);
age = input.nextInt();
stop = true;
}
catch (InputMismatchException e)
{
System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ",name);
input.next(); // Clearing the buffer. This is important otherwise Infinite Loop will occur
}
} while( !stop );
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。