异常和无限循环 [英] exceptions and infinite loops

查看:80
本文介绍了异常和无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

假定满足前提条件,则在执行此方法时并在输入a之后 字符串来测试程序,我得到一个无限循环.为什么会出现此问题,我该如何解决?

Assuming the preconditions are met, when this method gets executed and after entering a string to test the program, I get an infinite loop. Why is this problem occurring and how would I fix it?

推荐答案

为避免在引发异常时发生无限循环,必须跳过当前行并移至下一行进行处理.当前,当引发异常时,您正在重复迭代并扫描同一行,再次引发异常,因此您陷入了无限循环.

To avoid infinite loop when the exception is thrown, you must skip the current line and move on to the next line for processing. Currently, when the exception is thrown, you are re-iterating and scanning the same line which again throws exception and hence you are stuck in infinite loop.

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

I think you need to write the scan.nextLine() method call when an exception is thrown.

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位数.使用<>进行整数比较,而不是将数字转换为字符串.

Also modify the logic to detect if the number is 4 digit or not. Use integer comparison using< and > instead of converting the number into string.

这篇关于异常和无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆