public class A1Q2 { public static void main(String[] args) { final int RADIUS = 6371; int numCities, iterator, i; double[] latitudes, longitudes; String[] names, locations; String line; BufferedReader in = new BufferedReader(new FileReader("locations.txt")); line = in.readLine(); numCities = Integer.parseInt(line); line = in.readLine(); iterator = 0; i = 0; while (line != null) { if (iterator == 0) { names[i] = line; iterator++; } else if (iterator == 1) { latitudes[i] = Double.parseDouble(line); iterator++; } else if (iterator == 2) { longitudes[i] = Double.parseDouble(line); iterator++; } else { i++; iterator = 1; names[i] = line; } line = in.readLine(); } BufferedReader in = new BufferedReader(new FileReader("locationnames.txt")); line = in.readLine(); i = 0; while (line != null) { locations[i] = line; i++; line = in.readLine(); } for (int i = 0; i < locations.length; i++) { if (i + 1 <= locations.length) { if (hasValue(names,locations[i])) { printDistance(locations[i],locations[i+1], latitudes[getArrayPos(names,locations[i])],longitudes[getArrayPos(names,locations[i])], latitudes[getArrayPos(names,locations[i+1])],longitudes[getArrayPos(names,locations[i+1])]); } else { System.out.println("Location not found: " + locations[i]); } } } } public static void printDistance(String loc1, String loc2, double lat1, double long1, double lat2, double long2) { double a,c,d; a = Math.sin2((lat2 - lat1)/2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin2((long2 - long1)/2); c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); d = Math.round((RADIUS * c) * 10) / 10; System.out.println("Distance from " + loc1 + " to " + loc2 + ": " + d + " km."); } public static boolean hasValue(String[] names, String name) { boolean has = false; for (int i = 0; i < names.length; i++) { if (names[i].equals(name)) { } has = true; } } return has; } public static int getArrayPos(String[] names, String name ) { int pos = 0; for (int i = 0; i < names.length; i++) { if (names[i].equals(name)) { } pos = i; } } return pos; } }