-
-
Save bytecodeman/5a9edc7169a0d8e82029a99fa91e9f8a to your computer and use it in GitHub Desktop.
CSC-220 City Distance Data Class that read info from URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Chapter8ArrayExamples; | |
import java.io.IOException; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.util.Scanner; | |
public class CityDistanceData4 { | |
private static String cities[]; | |
private static double distMatrix[][]; | |
static { | |
try { | |
initDistanceMatrix("https://cs.stcc.edu/~silvestri/CityDistanceData/DistanceData2.txt"); | |
} | |
catch (Exception ex) { | |
System.out.println(ex); | |
} | |
} | |
private static int cityToIndex(String city) { | |
for (int i = 0; i < cities.length; i++) | |
if (cities[i].equals(city)) | |
return i; | |
return -1; | |
} | |
private static void initDistanceMatrix(String strURL) throws MalformedURLException, IOException { | |
Scanner input = new Scanner(new URL(strURL).openStream()); | |
int size = input.nextInt(); | |
input.nextLine(); | |
cities = new String[size]; | |
for (int i = 0; i < cities.length; i++) { | |
cities[i] = input.nextLine(); | |
} | |
distMatrix = new double[size - 1][]; | |
for (int row = 0; row < distMatrix.length; row++) { | |
distMatrix[row] = new double[row + 1]; | |
} | |
for (int row = 0; row < distMatrix.length; row++) { | |
for (int col = 0; col < distMatrix[row].length; col++) { | |
distMatrix[row][col] = input.nextInt(); | |
} | |
} | |
input.close(); | |
} | |
public static double distance(String start, String dest) { | |
int row = cityToIndex(start); | |
if (row == -1) { | |
System.err.println("Illegal Start City: " + start); | |
return -1; | |
} | |
int col = cityToIndex(dest); | |
if (col == -1) { | |
System.err.println("Illegal Destination City: " + dest); | |
return -1; | |
} | |
if (row == col) | |
return 0; | |
if (row > col) | |
return distMatrix[row - 1][col]; | |
return distMatrix[col - 1][row]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment