# Thread: Problem comparing three numbers

1. Member Join Date
Dec 2007
Posts
31
Rep Power
0

## 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;
}  Reply With Quote

2. ## 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.

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

Java 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

Java 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.
Last edited by jelly; 02-09-2008 at 05:46 PM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•