0
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...

2 Answers2

1

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());

xingbin
  • 27,410
  • 9
  • 53
  • 103
1

Your uLim (upperLimit) is below the lLim (lowerLimit):

   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 would order numbers according to their size, as in your call, not in the declaration.

user unknown
  • 35,537
  • 11
  • 75
  • 121
  • Ah, thank you. So the problem was in the declaration. I meant for uLim to be 99 and lLim to be 1 (upperLim and lowerLim), so it seems that’s what I got mixed up. – Nameless King Feb 04 '18 at 15:18