How to check for integer and less than or equal to 100 in an if/else statement

I have an if/else statement with a scanner in the conditions, as well as an && statement checking for the input being 100 or less. It goes like this:

Scanner input = new Scanner(System.in);

if(input.hasNextInt() && avgBefore <= 100) {
    avgBefore = input.nextInt();                
}

But if I put a number over 100 in, it still accepts it. Any help?

Jon Skeet
people
quotationmark

You're checking the value before you assign a new value to it. You need to assign the value from nextInt(), then check whether it's in range. For example:

if (input.hasNextInt()) {
    int candidate = input.nextInt();
    if (candidate <= 100) {
        avgBefore = candidate;
    } else {
        // Whatever you want to do on invalid input
    }
}

That's assuming you want to avoid assigning invalid values to avgBefore. If that's not an issue, you can use:

if (input.hasNextInt()) {
    avgBefore = input.nextInt();
    if (avgBefore > 100) {
        // Whatever you want to do on invalid input
    }
}

people

See more on this question at Stackoverflow