1
    // Precondition: number provided is a positive integer
    // Postcondition: returns a integer of length 4
     public static int validateNumber(int num, Scanner scan)
{
    int number = num;
    while(number < 1000 || number > 9999)
    {
        try
        {
            System.out.print("Number must be 4 digits long. Please provide the number again: ");
            number = scan.nextInt();    // reads next integer provided                                      
            scan.nextLine();
        }
        catch(InputMismatchException e) //outputs error message if value provided is not an integer
        {
            System.out.println("Incorrect input type.");
        }
    }
    return number;
}

假设满足前提条件,当这个方法被执行并输入一个字符串来测试程序后,我得到一个无限循环。为什么会出现这个问题,我该如何解决?

4

4 回答 4

3

为避免抛出异常时出现无限循环,您必须跳过当前行并移至下一行进行处理。目前,当抛出异常时,您正在重新迭代并扫描再次抛出异常的同一行,因此您陷入无限循环。

我认为您需要在scan.nextLine()引发异常时编写方法调用。

catch (InputMismatchException e) // outputs error message if value provided is not an integer
            {
                System.out.println("Incorrect input type.");
                // Moved the nextLine() method call over here
                scan.nextLine();
            }

还要修改逻辑以检测数字是否为 4 位。使用整数比较<,而>不是将数字转换为字符串。

于 2013-12-23T10:13:56.880 回答
2

为什么不

number < 1000 || number > 9999

代替

String.valueOf(number)).length() != 4

它看起来更干净,可能更有效。

于 2013-12-23T10:17:53.290 回答
0

代码看起来不错,但请考虑一下:

while ((int)Math.log10(number) != 3)
于 2013-12-23T10:22:14.360 回答
0

我可以看到的一个问题只是仔细查看您的 try catch 块-

如果您输入一个非整数输入,则scanner.nextInt() 将抛出一个InputMisMatchException 并且控件将来捕获块,因此最终不会为该数字分配一个新值,因此再次满足条件,因为它与前一个数字本身进行检查.

试试它是否有效,如果无效,请发送您的输入案例,以便我们分析并告诉我们您传递的方法中 num 的初始值是多少。

于 2013-12-23T10:31:47.790 回答