I'm working on a code which prints an array of locations, either in ascending or descending order. However, the formatting is all wrong for two out of 12 locations.
Code:
import java.util.*;
import static java.lang.System.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
class airwaysReservation {
static Scanner sc = new Scanner(System.in);
static String src[] = {"Mumbai", "London", "Hiroshima", "Lagos", "Minsk", "Baghdad", "Istanbul", "Delhi", "Fez", "Beijing", "Taipei", "Havana"};
static String dest[] = {"Hyderabad", "Paris", "Athens", "Alexandria", "Seoul", "Hamburg", "Bengaluru", "Rome", "Montreal", "Saitama", "Philadelphia", "Pune"};
public static void sortAsc(String arr[]) {
Arrays.sort(arr);
}
public static void sortDesc(String arr[]) {
//using libraries java.util.Arrays, and java.util.Collections, sorts arrays
Arrays.sort(arr, Collections.reverseOrder());
}
public static void list() {
out.println("Sources \t Destinations");
for (int i = 0; i< 12; i++) {
out.println(src[i] + "\t \t " + dest[i]);
}
}
public static void main(String[] args) {
out.println("Welcome \n Would you like to see the sources in ascending, or descending order?");
// stores ascending or descending for later
char schoice = sc.next().charAt(0);
out.println("Would you like to view the destinations in ascending, or descending order?");
// stores ascending or descending for later
char dchoice = sc.next().charAt(0);
switch (schoice) {
case 'a' :
sortAsc(src);
break;
case 'd' :
sortDesc(src);
break;
default:
out.println("Invalid choice");
}
switch (dchoice) {
case 'a' :
sortAsc(dest);
break;
case 'd' :
sortDesc(dest);
break;
default:
out.println("Invalid choice");
}
list();
}
}
The output for this, choosing ascending and then descending comes out to be:
Sources Destinations
Baghdad Seoul
Beijing Saitama
Delhi Rome
Fez Pune
Havana Philadelphia
Hiroshima Paris
Istanbul Montreal
Lagos Hyderabad
London Hamburg
Minsk Bengaluru
Mumbai Athens
Taipei Alexandria
I have a feeling this issue is because of different word lengths, however, that doesn't seem to affect the last few lines (eg Minsk and Bengaluru). How would I go about making all the destinations start from the same vertical line? Any help will be appreciated, thanks!