# Problem comparing three numbers

• 02-09-2008, 04:56 PM
gammaman
Problem comparing three numbers
For some reason when I compare the following and look to find the largest and smallest of three numbers, it results with the largest and smallest being the same number, which is the large number, Please help

//finding the largest and smallest numbers
if ((num1>num2) && (num1>num3));
{
large = num1;
}
else
if ((num2>num1) && (num2>num3));
{
large = num2;
}
else
if ((num3>num1) && (num3>num2));
{
large = num3;
}
else
if ((num1<num2) && (num1<num3));
{
small = num1;
}
else
if ((num2<num1) && (num2<num3));
{
small = num2;
}
else
if ((num3<num1) && (num3<num2));
{
small = num3;
}
• 02-09-2008, 06:43 PM
jelly
There seem to be two problems with the above code. Firstly it won't compile so I am surprised you got any result., if conditions should not end with a ;, and else clauses need to be in { } pairs, i.e.

Code:

```if ((num2<num1) && (num2<num3)); { small = num2; } else if ((num3<num1) && (num3<num2)); { small = num3; }```
needs to be rewritten (using your formatting)

Code:

```if ((num2<num1) && (num2<num3)) {     small = num2; }     else {     if ((num3<num1) && (num3<num2))     {         small = num3;     } }```
Secondly, even if you tidy up the syntax you find that the setting of the smallest number never happens because it always an else clause that never gets triggered. I suspect you wanted to find the largest and then the smallest number separately, try the following very quick and dirty class based on your algorithm

Code:

```public class Test42 {     public static void main (String[] args){         testNumbers();     }     public static void testNumbers(){         int num1 = 31, num2 = 76, num3 =54;         int small = -1, large = -1;         // calculate largest         if((num1 > num2)&&( num1 > num3)){             large = num1;         } else {             if((num2>num1)&&(num2>num3)){                 large = num2;             } else {                 if((num3>num1)&&(num3>num2)){                     large = num3;                 }             }         }         //calculate smallest         if((num1<num2)&&(num1<num3)){             small = num1;         } else {             if((num2<num1)&&(num2<num3)){                 small = num2;             } else {                 if((num3<num1)&&(num3<num2)){                     small = num3;                 }             }         }         // print results         System.out.println(large +"**"+small);             } }```
Have a look through it and see the differences and how it works. Also something to think about, your current algorithm will not work if two numbers are the same and either the largest or the smallest.