简体   繁体   中英

Why do I get infinite recursion warning in this piece of code, despite it not being infinite?

So I wrote a piece of code that is supposed to catch wrong format of input, and ask the user for correction. It works correctly, does exactly what it is supposed to do, but Netbeans throws "the method validate will recurse infinitely" warning. I tested it thoroughly and it does not indeed recurse infinitely, so I would like to know what possibly makes Netbeans think that it will.

Edit: I realized now that the int validatedInput = 0; is culpript here. If user enters char, it is still set to zero and the loop breaks off. But my main point is still why Netbeans actually thinks this piece of code has possibility of recursing infinitely, despite there are constraints in place that prevent it.

Here is the following method(note that maxBound is always predefined by array lenght):

public static int validate(int maxBound) {
    int controlVar = maxBound;
    Scanner scan = new Scanner(System.in);
    boolean wrongInputLoopThrough = false;
    int validatedInput = 0;
    do {
        if (wrongInputLoopThrough) {
            System.out.println("Integer value is out of bound! Please repeat your input.");
        }
        try {
            validatedInput = Integer.parseInt(scan.nextLine());
            wrongInputLoopThrough = true;
        } catch (NumberFormatException e) {
            System.out.println("Not a number, please enter a number");
            validatedInput = validate(controlVar); //here is my recursion to return control flow back to the top of the method
        }
    } while (validatedInput < 0 || validatedInput > controlVar);
    return validatedInput;
}

You call validate again in your catch, so if it is invalid and you are passing the same value it could catch indefinitely. Instead of catching you should just continue the loop like if it was an integer outside the bounds...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM