InputMisMatch异常错误

时间:2017-10-28 09:08:33

标签: java exception-handling inputmismatchexception

我正在尝试编写此程序,该程序会询问用户x1的值,并在用户输入除整数之外的其他内容时创建异常。但是,当我使用InputMismatchException时,我不断收到错误消息,说它无法转换为throwable?

这是我的代码:

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int x1 = getScannerInt("Enter x1");

}

public static int getScannerInt(String promptStr) {
    Scanner reader = new Scanner(System.in);
    int x1 = 1;
    boolean continueLoop = true;
    while (continueLoop) {
        System.out.println("Enter x1: ");
    }
    {
        try {
            x1 = reader.nextInt();
            continueLoop = false;
        } catch (InputMismatchException e) {
            System.out.println("Please only enter numbers");

        }
    }
    return x1;

}

我将不胜感激任何帮助!

1 个答案:

答案 0 :(得分:0)

您必须使用reader.nextLine();这样使用新行:

while (continueLoop) {
    System.out.println("Enter x1: ");
    try {
        x1 = reader.nextInt();//this does not consume the last newline
        continueLoop = false;
    } catch (InputMismatchException e) {
        System.out.println("Please only enter numbers");
    }
    reader.nextLine();//You can consume it using nextLine()
}

注意:

使用时

while (continueLoop) 
     System.out.println("Enter x1: ");

System.out.println("Enter x1: ");之后唯一有效的指令,请小心。

相关问题