AfterShock360
AfterShock360

Reputation: 165

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?

Upvotes: 0

Views: 2185

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500785

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

Upvotes: 4

Juan Carlos Mendoza
Juan Carlos Mendoza

Reputation: 5794

As already said, you must assign the value and then check if is <= 100. A less readable but one-liner solution can be:

if(input.hasNextInt() && (avgBefore = input.nextInt()) <= 100) { // assign the value and immediately test if is <= 100
    // whatever you want to do with `avgBefore`
}

Upvotes: 0

Related Questions