编程从键盘上输入一个整数,当输入的是非整数时会出现 InputMismatchException 异常。请编写程序
对此异常进行捕获处理。
我的代码如下:
import java.util.Scanner;
public class InputMismatchException {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
try {
int a=sc.nextInt();
System.out.println(a);
}catch (InputMismatchException e){
System.out.println("输入不为整型");
}
catch(Exception e) {
System.out.println("异常类型为");
}
}
}
请问大佬能帮我看看这代码有什么问题吗?为什么会显示不兼容类型,在相应try语句中不能抛出错误InputMismatchException?谢谢!
问题在于你定义的类名和工具类名重名了。
可能工具InputMismatchException 包都没有导入,直接使用了定义的类作为异常类。
解决方式:
1、修改你的类名,不要和工具类InputMismatchException 同名。
2、使用全限定路径类名。java.util.InputMismatchException
import java.util.Scanner;
public class InputMismatchException {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
try {
int a=sc.nextInt();
System.out.println(a);
}catch (java.util.InputMismatchException e){
System.out.println("输入不为整型");
}
catch(Exception e) {
System.out.println("异常类型为");
}
}
}
程序没有问题,但异常类型不对,应该是抛出NumberFormatException异常。
第八行改为以下:
}catch (java.util.InputMismatchException e){