-->

异常和无限循环(exceptions and infinite loops)

2019-10-19 04:05发布

    // 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;
}

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

Answer 1:

为了避免无限循环,当异常被抛出,你必须跳过当前行并移动到用于处理下一行。 目前,当异常被抛出,你重新迭代和扫描再次抛出异常,因此你是停留在无限循环的同一行。

我想你需要写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位或没有。 使用使用整数比较<>而不是数字转换成字符串。



Answer 2:

为什么不

number < 1000 || number > 9999

代替

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

它看起来更清洁,可能是更有效的。



Answer 3:

有一个问题我可以看到刚才看到你的try catch块carefully-

如果你输入一个非整数输入,然后scanner.nextInt()将抛出InputMismatchException时和控制会来赶块所以最后一个新值不分配给数量如此反复条件满足,因为它与先前的数字本身检查。

只是尝试,如果它的作品,如果它不那么请把你输入的情况下,使我们可以分析,也告诉我们什么是方法要传递NUM的初始值。



Answer 4:

代码看起来不错,但考虑这个:

while ((int)Math.log10(number) != 3)


文章来源: exceptions and infinite loops