Skip to content

Instantly share code, notes, and snippets.

@naijab
Last active April 8, 2020 09:26
Show Gist options
  • Save naijab/c9e0ae23a8a322824285c40ab2989764 to your computer and use it in GitHub Desktop.
Save naijab/c9e0ae23a8a322824285c40ab2989764 to your computer and use it in GitHub Desktop.
Sort City with Alphabetical Order in Java
import java.util.Scanner;
public class SortThreeCity {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first city: ");
String cityOne = sc.nextLine();
System.out.print("Enter the second city: ");
String cityTwo = sc.nextLine();
System.out.print("Enter the third city: ");
String cityThree = sc.nextLine();
String cityFirst = getFirst(cityOne, cityTwo, cityThree);
String cityMiddle = getMiddle(cityOne, cityTwo, cityThree);
String cityLast = getLast(cityOne, cityTwo, cityThree);
System.out.print("The three cities with Alphabetical Order are: ");
System.out.println(cityFirst + ", " + cityMiddle + ", " + cityLast);
}
private static String getFirst(String a, String b, String c) {
String first = "";
if (a.compareToIgnoreCase(b) < 0 & a.compareToIgnoreCase(c) < 0) {
first = a;
} else if (b.compareToIgnoreCase(a) < 0 & b.compareToIgnoreCase(c) < 0) {
first = b;
} else {
first = c;
}
return first;
}
private static String getMiddle(String a, String b, String c) {
String middle = "";
if (a.compareToIgnoreCase(b) * a.compareToIgnoreCase(c) <= 0) {
middle = a;
} else if (b.compareToIgnoreCase(a) * b.compareToIgnoreCase(c) <= 0) {
middle = b;
} else {
middle = c;
}
return middle;
}
private static String getLast(String a, String b, String c) {
String last = "";
if (a.compareToIgnoreCase(b) > 0 & a.compareToIgnoreCase(c) > 0) {
last = a;
} else if (b.compareToIgnoreCase(a) > 0 & b.compareToIgnoreCase(c) > 0) {
last = b;
} else {
last = c;
}
return last;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment