In: Computer Science
Write a Java class called CityDistances in a class file called
CityDistances.java.
1. Your methods will make use of two text files.
a. The first text file contains the names of cities. However,
the first line of the file is a number specifying how many city
names are contained within the file. For example,
5
Dallas
Houston
Austin
Nacogdoches
El Paso
b. The second text file contains the distances between the cities
in the file described above. This file does not contain an entry
for how many distances are within the file. If, as in the example
above, there are five (5) city names in the first text file, then
this text file should contain 52 = 25 distance entries. The first
entry should always be zero (since Dallas is a distance of zero
miles from itself). The second entry is the distance from Dallas to
Houston, and the third entry is the distance from Dallas to Austin,
etc.
3. The CityDistances class contains four static methods: a. A
public method called loadCities() that opens the file, reads in the
data and returns a one-dimensional array of String containing the
city names stored in the file. The method takes a single argument
called filename of type String that is the name of the file to be
opened. The first item read from the text file should be the number
of city names within the file (read as an integer). If done
correctly, the returned array should be the correct size to store
all city names without any “extra” space within the array. If the
file does not exist or a problem reading the file is encountered,
then an IOException is thrown. Hint: Be aware that using the
nextInt() method from the Scanner class will read the number but
not the newline character found after the number. Your method
should correctly handle the newline character.
b. A public method called loadDistances() that opens the file,
reads in the data and returns a two-dimensional array of double
containing the city distances stored in the file. The method takes
an argument called filename of type String that is the name of the
file to be opened and an argument called numCities of type int
corresponding to the number of cities that were listed in the text
file read by loadCities(). If done correctly, the returned
two-dimensional array should be an n x n array where n is the
number of cities represented and organized such that each row
corresponds to the distances from a particular city. If the file
does not exist or a problem reading the file is encountered, then
an IOException is thrown.
c. A private method called getCityIndex() that takes two arguments:
the first called cities of type String[] (that is, the array of
city names), and the second called cityName of type String (that
is, the name of a particular city). The method iterates through the
array of city names and returns the index of the location within
the array that contains the value of cityName. If the string
specified by cityName is not found in cities, then the method
returns -1. Hint: In Java, you need to use the equals() method
found in the String class to compare two strings instead of the ==
operator.
d. A public method called findDistance that takes four arguments:
the first is called cities of type String[]; the second is called
distances of type double[][]; the third is called start of type
String; and the fourth is called end of type String. The method
makes use of the getCityIndex() helper method to retrieve the
indices of the city names corresponding to start and end arguments.
Then, the correct distance is retrieved from the distances array
and returned to the caller.
==============================
INPUT FILE: cityname.txt
==============================
5
Dallas
Houston
Austin
Nacogdoches
El Paso
==============================
INPUT FILE: citydistance.txt
==============================
0
25
31
45
29
25
0
56
35
41
31
56
0
77
39
45
35
77
0
93.5
29
41
39
93.5
0
===========================
JAVA PROGRAM
Filename: CityDistances.java
===========================
package test.city.distance;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class CityDistances {
private static final String FILE_CITY_NAMES =
"cityname.txt";
private static final String FILE_CITY_DISTANCES=
"citydistance.txt";
public static void main(String[] args){
String[] cities = null;
double[][] cityDistances =
null;
try{
cities =
loadCities(FILE_CITY_NAMES);
if(cities!=null){
cityDistances =
loadDistances(FILE_CITY_DISTANCES, cities.length);
}
}catch(IOException e){
System.out.println("ERROR: "+e.getMessage());
}
String startCity,endCity;
//valid data
startCity =
"Houston";endCity="Austin";
double d =
findDistance(cities,cityDistances,startCity,endCity);
if(d==-1){
System.out.println("Distance between "+startCity+" and "+endCity+"
is NOT FOUND!");
}else{
System.out.println("Distance between "+startCity+" and "+endCity+"
is: "+d);
}
//valid data
startCity =
"Nacogdoches";endCity="El Paso";
d =
findDistance(cities,cityDistances,startCity,endCity);
if(d==-1){
System.out.println("Distance between "+startCity+" and "+endCity+"
is NOT FOUND!");
}else{
System.out.println("Distance between "+startCity+" and "+endCity+"
is: "+d);
}
//invalid data, as new york is not
in the city list
startCity = "New
York";endCity="Dallas";
d =
findDistance(cities,cityDistances,startCity,endCity);
if(d==-1){
System.out.println("Distance between "+startCity+" and "+endCity+"
is NOT FOUND!");
}else{
System.out.println("Distance between "+startCity+" and "+endCity+"
is: "+d);
}
}
/**
* load city names from given filename
* @param filename
* @return
* @throws IOException
*/
public static String[] loadCities(String filename)
throws IOException{
Scanner fileScanner = null;
try{
fileScanner =
new Scanner(new File(filename));
}catch(FileNotFoundException
fe){
throw new
IOException("File "+filename+" Not Found!");
}
String[] cityNames = null;
int counter = 0;
int numOfCities = 0;
int cityIndex = 0;
while(fileScanner.hasNextLine()){
counter++;
if(counter==1){
try{
numOfCities =
Integer.parseInt(fileScanner.nextLine());
}catch(NumberFormatException nfe){
fileScanner.close();
throw new IOException("File
"+filename+" is not properly formatted!");
}
cityNames = new String[numOfCities];
cityIndex = 0;
}else{
String currentString =
fileScanner.nextLine().trim();
if(!currentString.equals("")){
cityNames[cityIndex++] =
currentString;
}
}
}
fileScanner.close();
if(numOfCities!=cityIndex){
throw new
IOException("citynames did not match the count of city given in the
file "+filename+" !");
}
return cityNames;
}
/**
* load distances from given filename and
numCities
* @param filename
* @param numCities
* @return
* @throws IOException
*/
public static double[][] loadDistances(String
filename,int numCities) throws IOException{
Scanner fileScanner = null;
try{
fileScanner =
new Scanner(new File(filename));
}catch(FileNotFoundException
fe){
throw new
IOException("File "+filename+" Not Found!");
}
double[][] distances = new
double[numCities][numCities];
int rowIndex = 0;
int colIndex = 0;
while(fileScanner.hasNextLine()){
String
currentLineData = fileScanner.nextLine().trim();
double
distance;
try{
distance =
Double.parseDouble(currentLineData);
}catch(NumberFormatException nfe){
fileScanner.close();
throw new IOException("File "+filename+" is not
properly formatted!");
}
if(colIndex==numCities){
rowIndex++;
colIndex = 0;
}
distances[rowIndex][colIndex++]= distance;
}
fileScanner.close();
//after coming out of the loop the
(rowIndex+1) should become equal to numCities
//as there should be numCities *
numCities number of entries
if(rowIndex+1!=numCities){//
throw new
IOException("File "+filename+" is not properly formatted!");
}
return distances;
}
/**
* get index of given city name
* -1 if city name not found in cities array
* @param cities
* @param cityName
* @return
*/
private static int getCityIndex(String[] cities,String
cityName){
int cityIndex = -1;
for(int i = 0; i < cities.length
; i++){
if(cities[i].equals(cityName)){
cityIndex = i;
break;
}
}
return cityIndex;
}
/**
* find distance between start and end city
* return distance (-1 if not found)
* @param cities
* @param distances
* @param start
* @param end
* @return
*/
public static double findDistance(String[] cities,
double[][] distances,String start,String end){
int startCityIndex =
getCityIndex(cities, start);
int endCityIndex =
getCityIndex(cities, end);
if(startCityIndex!=-1 &&
endCityIndex!=-1){
return
distances[startCityIndex][endCityIndex];
}else{
return -1;
//indicating not found
}
}
}
============================================
OUTPUT
============================================
Distance between Houston and Austin is: 56.0
Distance between Nacogdoches and El Paso is: 93.5
Distance between New York and Dallas is NOT
FOUND!