0

首先,这是我的一门课作业。我理解我的教授试图用这个作业解释的所有概念,但我有一个愚蠢的问题,它不断循环,不知道如何阻止它。

我们需要创建自己的 Exception 类,并在创建 Time(包括小时、分钟和秒)对象时在特定实例中使用 throw 它们。但是,我自己的异常类没有问题,我遇到了 InputMismatchException 连续执行的问题。

此类通过 Scanner 对象读取文件,该对象有几行,每行由三个整数组成,以军事格式(例如 20 15 33)表示时间为 8:15:33 PM,但一旦存在无效令牌(例如 20 15 33 ,其中 20 不是整数)它不会停止 InputMismatchException 捕获块。

这是代码:

public class TimeTestNew
{

public static void main (String[] args)throws IllegalHourException,
        IllegalMinuteException,
        IllegalSecondException,
        FileNotFoundException,
        NumberFormatException
{
    boolean fileFound = false;

    while(!fileFound)
    {
        String input = JOptionPane.showInputDialog("Enter filename: " );

        try
        {
            Scanner in = new Scanner(new File(input));
            fileFound = true;

            while(in.hasNextLine())
            {
                int hour = 0, minute = 0, second = 0;
                try
                {
                    hour = in.nextInt();
                    minute = in.nextInt();
                    second = in.nextInt();
                    Time theTime = new Time(hour,minute,second);
                    System.out.println(theTime);
                }
                catch(IllegalHourException e)
                {
                    System.err.println("Sorry, \"" + e.value 
                            + "\" is an invalid hour.");
                }
                catch(IllegalMinuteException e)
                {
                    System.err.println("Sorry, \"" + e.value 
                            + "\" is an invalid minute.");
                }
                catch(IllegalSecondException e)
                {
                    System.err.println("Sorry, \"" + e.value 
                            + "\" is an invalid second.");
                }
                catch(NumberFormatException | InputMismatchException e)
                {
                    System.err.println("Incorrect format used.");
                    // this is what keeps getting executed

                }

            }

            in.close();

        }
        catch (FileNotFoundException e)
        {
            System.err.println("ERROR: \"" + input + "\" not found\n"
                    + "Please enter a valid filename.");
        }
    }
}
}

这是示例输出:

12:12:12 P.M.
Sorry, "24" is an invalid hour.
1:02:03 A.M.
1:13:13 P.M.
Sorry, "90" is an invalid minute.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
Incorrect format used.
//...and this goes on forever

如您所见,它将一遍又一遍地在 InputMismatchException 的 catch 块内循环“使用的格式不正确”......我无法找到一种方法让它停止并继续读取文件。

任何帮助将不胜感激解释解决方案,谢谢!

4

1 回答 1

1

问题是 while 循环的条件不是输入是否有效,而是文件中是否存在下一行。如果您无法在 while 循环之前验证输入,则应该检查 break 语句。

于 2014-12-04T15:34:14.273 回答