How can I order any three variable values in alphabetical order using if else statements only?

Liam :

Using if else statements not arrays how can I order any three variable values string values in alphabetical order? Therefore, if I change the value of 'w' variable it will still work.

Overall, the issue I'm having at the moment is even being able to put any string values assigned to the variable into alphabetical order. I was wondering if anyone could help me please?

Incase you ask why not arrays is because for the thing I'm working on I can't use them.

The below code represents what I was wondering on.

String w = "York";
String k = "Oxford";
String t = "Sam";

if ((w.compareTo(k) <= 0) && (k.compareTo(t) <= 0)) {
    System.out.println(k);
    System.out.println(w);
    System.out.println(t);
} else if ((w.compareTo(t) <= 0) && (k.compareTo(t) <= 0)) {
    System.out.println(k);
    System.out.println(w);
    System.out.println(t);
} else if ((t.compareTo(w) <= 0) && (w.compareTo(k) <= 0)) {
    System.out.println(t);
    System.out.println(w);
    System.out.println(k);
} else if ((t.compareTo(k) <= 0) && (k.compareTo(w) <= 0)) {
    System.out.println(w);
    System.out.println(t);
    System.out.println(k);
} else if ((k.compareTo(w) <= 0) && (w.compareTo(t) <= 0)) {
    System.out.println(w);
    System.out.println(k);
    System.out.println(t);
} else {
    System.out.println(k);
    System.out.println(t);
    System.out.println(w);
}

}
}
Andreas :

To save on amount of code and on number of comparison calls, I'd do it kind of like an insertion sort:

String w = "York";
String k = "Oxford";
String t = "Sam";

String s1, s2, s3;
// insert first 2 values in correct order
if (w.compareTo(k) <= 0) {
    s1 = w;
    s2 = k;
} else {
    s1 = k;
    s2 = w;
}
// insert 3rd value in correct place
if (s2.compareTo(t) <= 0) {
    s3 = t;
} else {
    s3 = s2;
    if (s1.compareTo(t) <= 0) {
        s2 = t;
    } else {
        s2 = s1;
        s1 = t;
    }
}

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);

Output

Oxford
Sam
York

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305806&siteId=1