【问题标题】:InputMismatchException Error输入不匹配异常错误
【发布时间】:2012-07-01 11:20:53
【问题描述】:

我收到一个编译时错误提示:

不能抛出 InputMismatchException 类型的异常;异常类型必须是 Throwable InputMismatchException.java 的子类

据我所知 InputMismatchException 是 Scanner 在收到无效输入时抛出的异常,为什么这个错误会阻止我编译?

import java.util.*;
public class InputMismatchException
{
public static void main(String[] args)
{
    boolean continueInput = true;
    Scanner input = new Scanner(System.in);
    do
    {
        try
        {
            System.out.println("Enter an integer: ");
            int num = input.nextInt();
            System.out.println("You entered: " + num);
            continueInput = false;
        }
        catch (InputMismatchException e) //This is where the error occurs.
        {
            System.out.println("Enter an integer!");
            input.nextLine();
        }
    }while(continueInput);
}
}

【问题讨论】:

    标签: java exception error-handling standard-library


    【解决方案1】:

    尝试为您的班级使用不同的名称。当你有一个名为InputMismatchException 的类已经是一个异常类的名称时,你会混淆编译器。

    【讨论】:

    • 成功了!非常感谢!我知道这很简单!所以它给我一个错误的原因是因为它认为我将该类用作异常类,它不是!我不敢相信我是个菜鸟!
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    相关资源
    最近更新 更多