Integer Comparison, Outputting Largest Integer Not Working

• 10-16-2011, 06:54 AM
killingthemonkey
Integer Comparison, Outputting Largest Integer Not Working
I'm writing a Java program to take three integers and output the smallest, largest, sum, and average. Everything works except for finding the highest integer. If I set number1 to 1 and number2 to 2 and number3 to 3, the program outputs 2 as largest. If I do it in this order 3, 1, 2, it puts out 3 as the largest. The bit of code to output the smallest integer works. I include it for comparison. Thanks.

Code:

```        if (number1 < number2 || number1 < number3)             smallest = number1;         else if (number2 < number1 || number2 < number3)             smallest = number2;         else if (number3 < number1 || number3 < number2)             smallest = number3;                 if (number1 > number2 || number1 > number3)             largest = number1;         else if (number2 > number1 || number2 > number3)             largest = number2;         else if (number3 > number1 || number3 > number2)             largest = number3;           System.out.printf("The smallest of the numbers is %d.\n", smallest);         System.out.printf("The largest of the numbers is %d.\n", largest);```
• 10-16-2011, 07:01 AM
JosAH
Re: Integer Comparison, Outputting Largest Integer Not Working
And if you test the numbers 2, 1, 3 it outputs 2 as the smallest number; those if-statements are completely incorrect. Have a look at the Math.min( ... ) and Math.max( ... ) methods instead.

kind regards,

Jos

ps. or if you insist of doing it all yourself, change the || (inclusive or) to && (logical and) operator.
• 10-16-2011, 07:08 AM
killingthemonkey
Re: Integer Comparison, Outputting Largest Integer Not Working
Thanks, JosAH.

I didn't even know there were Math.min and Math.max methods. My book hasn't got that far into it. I'm using Deiltel's Java How to Program.
• 10-16-2011, 07:42 AM
JosAH
Re: Integer Comparison, Outputting Largest Integer Not Working
Quote:

Originally Posted by killingthemonkey
Thanks, JosAH.

I didn't even know there were Math.min and Math.max methods. My book hasn't got that far into it. I'm using Deiltel's Java How to Program.

I personally prefer the methods over a hand crafted solution; have a look, the following fragment sorts things out given the numbers a, b and c:

Code:

```int max= Math.max(Math.max(a, b), c); int min= Math.min(Math.min(a, b), c); int mid= a+b+c-max-min;```
kind regards,

Jos
• 10-16-2011, 08:59 PM
killingthemonkey
Re: Integer Comparison, Outputting Largest Integer Not Working
Thanks, again. That actually works better than the handcrafted version. My version threw a bad result if two of the numbers were equal to each other. Yours works correctly.