Search code examples
javaloopsiojava.util.scannerdo-while

Java: Infinite looping within while loop when trying to limit user input with do-while


static int prompt(set x) {
    Scanner input = new Scanner(System.in);
    do {
        System.out.println("Please enter an integer within the specified range.");
        while (!input.hasNextInt()) {
            System.out.println("Please enter a valid integer.");
            input.next();
        }
        System.out.println("input received");
        x.setVal(input.nextInt());
    } while (x.getVal() <= x.getlLim() || x.getVal() > x.getuLim());
    input.close();
    return x.getVal();
}

This method is supposed to limit user input to a user-defined range of integers, but it keeps looping within the do{...}while(...) loop even when I enter valid numbers. It is fed a static class set, which is initialized with a constructor. Here are the relevant fragments of code:

set constructor:

    set(int val, int uLim, int lLim) {
        this.val = val;
        this.uLim = uLim;
        this.lLim = lLim;
    }

Initializing set:

    set max = new set(0, 1, 99);

I then proceed to prompt(max), but it keeps telling me "Please enter...specified range" even though I enter a valid integer like 60, 55, or 10. Are there any problems with the loop or am I doing something wrong somewhere else?

Couldn't seem to figure this out, tried using regexs, try-catch blocks and parseInt as alternatives, ended up with different errors so I went back to this simplest method of regulating user input...


Solution

  • The loop condition is while (x.getVal() <= x.getlLim() || x.getVal() > x.getuLim());

    And you set uLim = 1, lLim = 99,

    Obviously, your "valid" number 1<= 60, 55, 10 <=99, that's why the loop never ends.

    According to your description, I think the loop condition should be while (x.getVal() >= x.getlLim() || x.getVal() < x.getuLim());