As part of a problem set I have to sort 3 numbers in ascending order. A simple enough task, but for some reason I’m not getting the expected result. Using arrays is not allowed. Below is my code; I’ve linked to my flowchart here. I cannot get the program to sort 3 numbers such as 5, 5, and -4. When I attempt that case, here is the output:
Enter three numbers.
In order -0.04 5.0 5.0In order 5.0 -0.04 5.0
If I get that one to work, I cannot get the case of 23, 0, 39 to sort. Not sure if I have over-complicated the attempt with so many cases; I feel that my flowchart covers all possibilities. Thanks in advance!
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter three numbers."); double x = reader.nextDouble(); double y = reader.nextDouble(); double z = reader.nextDouble(); if (x >= y){ if (y >= z) System.out.print("In order " + z + " "+ y + " " + x); if (z >= x) System.out.print("In order " + y + " "+ x + " " + z); if (x > z) System.out.print("In order " + y + " " + z + " " + x); } if (y > x) { if (z >= y) System.out.print("In order " + x + " " + y + " "+ z); if (z >= x) System.out.print("In order " + y + " " + x + " " + z); if (x > z) System.out.print("In order " + y + " " + z + " " + x); } } }
Advertisement
Answer
I WANT TO MAKE A CORRECTION of the most upvoted answer by Elliot Frisch.
There is the need to first check if both conditions are true so we can store the correct ‘max’ and ‘min’ number. Because on Elliot’s answer this is not checked and if they are both true, the ‘x’ will always be the number that is stored, and that will sometimes give incorrect outputs.
HOPE IT HELPS 🙂
You can solve this with no if
(s) using Math.max(double, double)
and Math.min(double, double)
and basic addition and subtraction. Like,
double max = Math.max(x, Math.max(y, z)); double min = Math.min(x, Math.min(y, z)); double mid = x + y + z - max - min; System.out.printf("In order %f %f %f%n", min, mid, max);
Using if
and else
comparisons instead of Math.max
and Math.min
is a little more complicated. Pick a default value and compare with the other two. Like,
double max = z; if (x > max && y > max) { if (x > y) { max = x; } else { max = y; } } if (x > max || y > max) { if (x > y) { max = x; } else { max = y; } } double min = z; if (x < min && y < min) { if (x < y) { min = x; } else { min = y; } } if (x < min || y < min) { if (x < y) { min = x; } else { min = y; } } double mid = x + y + z - max - min; System.out.printf("In order %f %f %f%n", min, mid, max);