java - InputMismatchException 被捕获后导致程序崩溃

标签 java exception inputmismatchexception

简介

我在捕获 InputMismatchException 时遇到问题。当我搜索 InputMismatchException 时,我已经阅读了该网站上出现在第一页上的所有线程。我在阅读这些帖子时找到了我的一个问题的答案;这个答案告诉我必须在导入语句中添加 import java.util.InputMismatchException; 。但是我遇到了一个不同的问题,我无法找到任何解决方案。最接近的其他问题是 this one 。我认为他和我有同样的问题,但该解决方案对我不起作用。

我的问题

我正在创建一个类来演示我创建的 ProductionWorker 数据类型。我想测试所有输入,以确保它们是可以按预期进行操作的有效输入。 我正在尝试获得工资率的双倍输入,如果输入错误,我希望被要求再次尝试输入;假设我不小心输入了“gary”而不是我的工资。我认为 try-catch-finally 可以工作,但进入 catch block 后我仍然得到 InputMismatchException...

控制台输出

run:
What is your name: gary
Please enter employee number: 88-m
Incorrect employee ID, please check it and try again.
Enter employee number: 888-m
Please enter hire date as "MM/DD/YYYY": 07/14/1994
Please enter shift (1 for day shift, 2 for night shift.: 2
Please enter rate of pay: $h
Rate of pay can only be digits.
Exception in thread "main" java.util.InputMismatchException
Examples: 30.00; 22.10; 7.25; 10.00
    at java.util.Scanner.throwFor(Scanner.java:864)
Please enter rate of pay: $ at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at programmingchallengeq1.ProgrammingChallengeQ1.main(ProgrammingChallengeQ1.java:69)
Picked up _JAVA_OPTIONS: -Xmx512m
C:\Users\nikru\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 15 seconds)

在我看来,因为 print 语句显示在控制台中,所以我将其放入了 catch block ,并且我认为如果将其放入 catch block ,异常就不会导致程序崩溃。我不知道我做错了什么...

代码

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package programmingchallengeq1;

import java.util.Scanner;
import java.util.regex.*;
import java.util.InputMismatchException;

public class ProgrammingChallengeQ1 {

    public static void main(String[] args) 
    {
        Scanner kb = new Scanner(System.in);
        final int SHIFT_LENGTH = 12;

        ProductionWorker workman = new ProductionWorker();
        System.out.print("What is your name: ");
        workman.set_name(kb.nextLine());
        System.out.print("Please enter employee number: ");
        // ask user for id and save it to workman
        workman.set_id(kb.nextLine());

        // while loop ensures that employee num matches specific format
        while (check_id(workman) == false)
        {
            System.out.print("Incorrect employee ID, please check it and" +
                    " try again.\n" + "Enter employee number: ");
            workman.set_id(kb.nextLine());
        }

        System.out.print("Please enter hire date as \"MM/DD/YYYY\": ");
        // ask user for date of hire and save it to workman
        workman.set_hire_date(kb.nextLine());
        // attempt to ensure a valid date was input with while loop
        while(check_date(workman) == false)
        {
            System.out.println("Date not recognized, please check date" +
                    " and try again.\n" + "Enter hire date as \"MM/DD/YYY\": ");
            workman.set_hire_date(kb.nextLine());
        }
        System.out.print("Please enter shift (1 for day shift, 2 for night"+
                " shift.: ");
        workman.set_shift(kb.nextInt());
        // the while loop checks if a correct value is stored for shift
        while(workman.get_shift() != 1 && workman.get_shift() != 2)
        {
            System.out.print("Unrecognized shift. Please enter a 1 for" +
                    " day shift, or 2 for night shift: ");
            workman.set_shift(kb.nextInt());
        }
        System.out.print("Please enter rate of pay: $");
        // attempt to ensure a valid rate of pay is input with try-catch
        // boolean is the exit condition for while loop, which only breaks
        // if the input is valid
        boolean valid_input = false;
        while (valid_input != true)
        {
            try
            {
                workman.set_pay_rate(kb.nextDouble());
                valid_input = true;
            }
            catch(InputMismatchException ex)
            {
                //System.out.println(ex.getMessage());
                System.out.print("Rate of pay can only be digits.\nExamples:" +
                    " 30.00; 22.10; 7.25; 10.00\nPlease enter rate of pay: $");
            }
            finally
            {
                workman.set_pay_rate(kb.nextDouble());
            }
        }

    }

    public static boolean check_id(ProductionWorker wrkr)
    {
        // creating a regex pattern to check against input employee ID
        // to avoid inputting error
        String id_format = "\\d{3}-[a-m]";
        Pattern id_pattern = Pattern.compile(id_format);
        // check id against compiled regex pattern and save to a bool
        Matcher id_matcher = id_pattern.matcher(wrkr.get_id());
        boolean id_matches = id_matcher.matches();
        return id_matches;
    }
    public static boolean check_date(ProductionWorker wrkr)
    {
        //same concept as in check_id()
        String date_format = "\\d{2}/\\d{2}/\\d{4}";
        Pattern date_pattern = Pattern.compile(date_format);
        Matcher date_matcher = date_pattern.matcher(wrkr.get_hire_date());
        boolean date_matches = date_matcher.matches();
        return date_matches;
    }
}

感谢所有帮助,谢谢!

最佳答案

您也在finally block 中运行nextDouble(),因此无论发生什么情况此时都会失败。基本上,失败的第一个调用不会消耗数据,因此第二个调用不会等待新的用户输入,它会立即尝试消耗已经存在的输入并再次失败。

您必须显式使用该行来解决此问题:

Scanner sc = new Scanner(System.in);
try {
    sc.nextDouble();
} catch (InputMismatchException e) {
    System.out.println("Oops, something went wrong...");
    sc.nextLine();
    sc.nextDouble();
}

我删除了 finally block ,因为我不明白为什么在第一次尝试成功时您还想重试该操作。

关于java - InputMismatchException 被捕获后导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52450075/

相关文章:

java - 我们可以访问java包外默认类中定义的公共(public)方法吗?

java - 查询嵌套文档数组以获得字段的最大值

c# - 防止 WCF 回调出现异常

java - (Java) 扫描仪未从文件中读取 nextDouble()

java - 增强groupReduce变换的并行化程度

exception - Haskell 中的安全应用

java.rmi.ServerException : RemoteException occurred in server thread (ClassNotFoundException)

java - 代码不久前工作然后 "java.util.InputMismatchException"

java - java 中的 nextFloat 问题

java - 如何在 Eclipse 中将断点切换到整个类?