Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Compare 3 integers, arrange largest, median and smallest

I have been assigned a homework assignment to prompt the user for 3 positive integers then compare and print them in order of largest, median and smallest.

Prompting and writing a while loop to check if the numbers are positive is fine. I can also figure out how to print the largest and smallest integer.

(Something like this?)

 if (a >= b) 
       if (a >= c) { max= a; if (b >= c) min= c; else min= b; }
       else { max= c; min= b; }
    else if (b >= c)
       { max= b; if (a >= c) min= c; else min= a; }
    else { max= c; if (a >= b) min= b; else min= a; }

How would I calculate the middle integer using this same schema? I would preferably not use an array yet as the professor has not yet explained them.

Any help is appreciated.

Thank you!

like image 928
andrsnn Avatar asked Jul 11 '13 22:07

andrsnn


1 Answers

Store the three numbers in three variables a b c, then use your branching logic to determine the order. You have everything you need to solve this problem here.

For example

if (a > b && a > c) {
    //Here you determine second biggest, but you know that a is largest
}

if (b > a && b > c) {
    //Here you determine second biggest, but you know that b is largest
}    

if (c > b && c > a) {
    //Here you determine second biggest, but you know that c is largest
}

Inside the comments above is where you would determine the median and the smallest number. The code is wordy, but since you said not to use an array, it's the most straightforward way to understand the problem.

like image 85
Kon Avatar answered Oct 24 '22 02:10

Kon