Question

In: Computer Science

Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods...

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.

Solutions

Expert Solution

==============================

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!


Related Solutions

1. Write a public Java class called WriteFile which opens an empty file called letters.dat. This...
1. Write a public Java class called WriteFile which opens an empty file called letters.dat. This program will read a String array called letters and write each word onto a new line in the file. The method should include an appropriate throws clause and should be defined within a class called TFEditor. The string should contain the following words: {“how”, “now”, “brown”, “cow”}
Write a class called VLPUtility with the following static methods: Java Language 1. concatStrings that will...
Write a class called VLPUtility with the following static methods: Java Language 1. concatStrings that will accept a variable length parameter list of Strings and concatenate them into one string with a space in between and return it. 2. Overload this method with two parameters, one is a boolean named upper and one is a variable length parameter list of Strings. If upper is true, return a combined string with spaces in upper case; otherwise, return the combined string as...
b) Name the class ArithmeticMethods, and the java file ArithmeticMethods.java. c) Write separate methods to perform...
b) Name the class ArithmeticMethods, and the java file ArithmeticMethods.java. c) Write separate methods to perform arithmetic operations of sum, average, product, max and min of three integer numbers. These 5 methods should have three integer parameters to take the three integer values. They should be valuereturn methods, and return the arithmetic result in proper data type when they are invoked (called). The average method should return a double value, and all the other methods should return integer values. d)...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called DataBaseManager as in Lecture 5 and create a database table in SQLite, called StudentInfo. The fields for the StudentInfo table include StudentID, FirstName, LastName, YearOfBirth and Gender. Include functions for adding a row to the table and for retrieving all rows, similar to that shown in lecture 5. No user interface is required for this question, t -Continuing from , follow the example in...
In Java Create a class called "TestZoo" that holds your main method. Write the code in...
In Java Create a class called "TestZoo" that holds your main method. Write the code in main to create a number of instances of the objects. Create a number of animals and assign a cage and a diet to each. Use a string to specify the diet. Create a zoo object and populate it with your animals. Declare the Animal object in zoo as Animal[] animal = new Animal[3] and add the animals into this array. Note that this zoo...
Create a Project and a Class called “FinalGrade” Write a Java program to compute your final...
Create a Project and a Class called “FinalGrade” Write a Java program to compute your final grade for the course. Assume the following (you can hard-code these values in your program). Assignments are worth 30% Labs are worth 40% Mid-term is worth 15% Final is worth 15% Ask for the grades in each category. Store them in a double variable. Print out the final percentage grade.           For example, Final Grade Calculation Enter percentage grades in the following order. Assignments,...
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called...
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called without instantiating the class and returns a random Date between Jan 1, 2000 and Dec 31, 2010.
Java - Write an abstract class called Shape with a string data field called colour. Write...
Java - Write an abstract class called Shape with a string data field called colour. Write a getter and setter for colour. Write a constructor that takes colour as the only argument. Write an abstract method called getArea()
. Write a function in JAVA called shorten that is defined in the class P8 and...
. Write a function in JAVA called shorten that is defined in the class P8 and shortens each element of an array of strings. Every string with more than two characters is cut down to its first two characters. For example, a program that uses the function shorten follows. public class P8 { public static void main(String args[]) { String x[] = {"CSCI", "1", "11", "Queens", "College", "CUNY"}; shorten(x); for (int i = 0; i < 6; i++) System.out.print(x[i] +...
Module 1 Program Write a complete Java program in a file called Module1Program.java that reads all...
Module 1 Program Write a complete Java program in a file called Module1Program.java that reads all the lyrics from a file named lyrics.txt that is to be found in the same directory as the running program. The program should read the lyrics for each line and treat each word as a token. If the line contains a double (an integer is also treated as a double) it should use the first double it finds in line as the timestamp for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT