Question: This is a Dijsktra Algorithm Project, I have some errors that prevent me from running the program. *an expert said I did not have the

This is a Dijsktra Algorithm Project, I have some errors that prevent me from running the program.

*an expert said I did not have the resources files posted so here it is. There also some new requirements for this project so im hoping they can help me with that as well.

This is the prompt with the requirements:

Objectives:

1. Understand Single-source shortest paths problem.

2. Understand Dijkstras Algorithm.

3. Develop a directed graph data structure based software.

Overview:

Develop an interactive software for city and route queries.

Project Description: This software is a menu driven graph application that solve problems such as finding the shortest paths between two cities, city information inquiry, add and delete route between the two cities chosen by user.

Functional Requirements:

1. The software builds a directed graph by reading the information from two resource files:

a. city.dat: This file contains information about cities, where each line has 5 attributes: City Number, City_Code (2 letters), Full_City_Name, Population, and Elevation.

b. road.dat: This file contains information about roads, where each line has 3 attributes: From_City, To_City, and Distance. Note that all roads are assumed to be one-way.

2. User menu:

a. Q: Query the city information by entering the city code. In this option, user will be asked to enter the letter Q first. Then the software will ask for city code in a new line. User will then enter the city code. Error handling requirements (see Functional Requirements section) apply. Upon successful input, the software displays the city information (the whole record) on screen..

b. D: Find the shortest distance between two cities. In this option, user will be asked to enter the letter D as the command. Then the software will ask for city codes in a new line. User will then enter two city codes in one line, separated by one space. Error handling requirements (see Functional Requirements section) apply. Upon successful input, the software must display a user-friendly result with detailing the distance and the route on screen.

c. I: Insert a road by entering two city codes and distance. In this option, user enters letter I as the command. The software will ask for two City Codes and the Distance, all in one line, separated by one space. Error handling requirements (see Functional Requirements section) apply. Upon successful input, the software must report the result to user on screen.

d. R: Remove an existing road by entering two city codes. In this option, user is asked to enter the letter R for command. Then the software will ask for two City Codes. User will enter them in one line, separated by a space. Error handling requirements (see Functional Requirements section) apply. Upon successful input, the software must report the result to user on screen.

e. H: Display this message. In this option, the software display a set of command to help user. Details refer to section Expected Results.

f. E: Exit. In this option, user enter the letter E to exit the software.

3. User can enter commands repeatedly without exiting the software

Engineering Requirements:

1. The software must be implemented in Java language.

2. The software must be written from scratch and use minimum Java library. Use excessive Java library will impact the points of this project you will get.

3. Create a Java Digraph (directed graph) class to store the city and road information.

4. The software must use Dijkstra Algorithm to find the shortest path between two cities.

5. Output: The entire user/software interaction is to be displayed on the Command Prompt only.

6. Output file isnt required for this project.

7. Addition and Removal of a road must follow directed graphs definition. 8. Distance between the two cities should be integer, not double.

9. Command must be one letter. Any other characters such as multiple letters, numbers, special characters or combination of any them arent accepted.

10. The software shall not exit unless user chooses to.

11. Error handling: The software must handle errors correctly and gracefully. If users input doesnt conform to the requirement, the software should display a message that will guide user to enter them correctly the next time. If the resources files cant be read, a proper warning message must be displayed and the software should exit. Non-Functional Requirements None.

Scope

1. Generic type support isnt required.

2. Use only Dijkstras algorithm for finding shortest paths.

3. Use the command line for user to provide information the software required.

4. Commands can be either a upper case or lower case letter.

5. Use Min-Heap..

Expected Results

Your program should resemble the following output (the user inputs are underlined):

Command? H

Q Query the city information by entering the city code.

D Find the minimum distance between two cities.

I Insert a road by entering two city codes and distance.

R Remove an existing road by entering two city codes.

H Display this message.

E Exit.

Command? Q

City code: LV 12 LV LEE VINING 8390 5983

Command? D

City codes: CH PM

The minimum distance between CHINO HILLS and POMONA is 143 through the route: CH, xxx, ..., xxx, PM.

Command? I

City codes and distance: GG BO 100

You have inserted a road from GARDEN GRPVE to BOSSTOWN with a distance of 100. Command? R

City codes: KV MP

The road from KERNVILLE and MOUNTAIN PASS doesn't exist.

Command? E

The resource files are here:

road.dat

1 19 36 1 4 212 1 2 732 2 9 111 2 1 66 2 12 29 2 19 14 2 17 65 3 2 17 3 11 38 3 14 122 3 17 211 3 1 390 3 18 78 3 9 11 4 3 273 4 5 29 4 12 42 5 4 122 5 16 12 5 20 102 5 9 32 6 5 211 6 1 62 6 8 132 6 12 871 7 11 122 7 2 200 7 13 81 7 4 41 7 1 20 7 14 11 8 6 5 8 3 210 8 16 74 9 2 95 9 11 2 9 7 120 9 20 11 10 12 121 10 20 653 10 3 925 11 2 81 11 12 219 11 4 90 11 16 211 12 19 122 12 8 390 12 5 98 12 7 122 12 3 11 13 9 9 12 17 121 13 17 26 13 1 719 13 20 832 14 20 219 14 10 182 14 9 13 14 3 22 15 6 22 16 11 73 16 18 98 17 20 190 17 1 77 17 11 21 17 12 93 17 9 200 18 10 33 18 16 940 18 8 29 18 20 121 18 15 33 19 2 322 19 5 74 19 6 219 19 10 111

city.dat

1 AN ANAHEIM 1273000 310

2 BK BAKERSFIELD 31100 390

3 BO BOSSTOWN 790 10

4 BR BREA CANYON 529000 1242

5 CH CHINO HILLS 52200 1381

6 ED EDWIN DOM 12 8719

7 FI FORT IRWIN 4120 932

8 GD GARDENA 653210 674

9 GG GARDEN GRPVE 913330 952

10 KV KERNVILLE 6530 3925

11 LI LAKE ISABELLA 981 2194 12 LV LEE VINING 8390 5983 13 MP MOUNTAIN PASS 76 7190

14 PD PARKER DAM 2190 1829

15 PM POMONA 698300 298

16 PR PICO RIVERA 189820 1190

17 SB SAN BERNADINO 1293200 1033 18 TR TORRANCE 169400 829

19 VV VICTORVILLE 57460 2190

20 WW WRIGHTWOOD 9234 7910

So far I have this code with some errors:

Main.java ------------------------------------------------- import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage;

import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner;

public class Main {

// Creates a scanner object to read user input. private static Scanner scanner = new Scanner(System.in);

// Variable for user input. private static String command = "";

// Digraph public static Digraph cityDigraph = new Digraph();

public static void main(String[] args) throws InterruptedException, IOException { System.out.println("Hello");

consoleVersion(); }

public static void consoleVersion() throws FileNotFoundException { String userInput = "";

String resourcesDirectory = System.getProperty("user.dir") + "\\src\\Resources\\";

// Read the city.dat file. String citiesData = readFile(resourcesDirectory + "city.dat", ","); ArrayList cities = createCities(citiesData); ArrayList> vertices = new ArrayList>(); for (int i = 0; i < cities.size(); i++) vertices.add(new Vertex(cities.get(i))); cityDigraph.setVertices(vertices);

// Read the road.dat file. String roadsData = readFile(resourcesDirectory + "road.dat", ","); ArrayList roads = createRoads(roadsData); for (Road road: roads) { Vertex fromCity = findCityByNumber(road.getFromCity()); Vertex toCity = findCityByNumber(road.getToCity()); double distance = road.getDistance();

if(!cityDigraph.insertEdge(fromCity, toCity, distance)) System.out.println("A road failed to be inserted."); }

ArrayList edgeData; Vertex fromCity; Vertex toCity; double distance;

System.out.println( "Graph "); do { // Asks user to enter a command. System.out.print("Command? "); command = scanner.nextLine().toUpperCase();

switch (command) { case "D": System.out.print("City codes: "); userInput = scanner.nextLine().toUpperCase(); edgeData = parseStringToStrings(userInput, "[ ]+"); fromCity = findCityByCode(edgeData.get(0)); toCity = findCityByCode(edgeData.get(1));

ArrayList> path = cityDigraph.shortestDistance(fromCity, toCity);

System.out.print("The minimum distance between " + fromCity.getData().getCityName() + " and " + toCity.getData().getCityName() + " is " + " trough the route: "); for (int i = 0; i < path.size(); i++) { System.out.println(path.get(i).getData().getCityCode()); } break; case "E": System.exit(0); return; case "H": System.out.println( " Q - Query the city information by entering the city code. " + " D - Find the minimum distance between two cities. " + " I - Insert a road by entering two city codes and distance. " + " R - Remove an existing road by entering two city codes. " + " H - Display this message. " + " E - Exit. "); break; case "I": System.out.print("City codes and distance: "); userInput = scanner.nextLine().toUpperCase(); edgeData = parseStringToStrings(userInput, "[ ]+");

if(edgeData.size() != 3) { System.out.println("You're missing an item."); break; }

fromCity = findCityByCode(edgeData.get(0)); toCity = findCityByCode(edgeData.get(1)); distance = Double.valueOf(edgeData.get(2));

if(fromCity != null && toCity != null) { if(cityDigraph.insertEdge(fromCity, toCity, distance)) System.out.println("You have inserted a road from " + fromCity.getData().getCityName() + " (" + fromCity.getData().getCityCode() + ") to " + toCity.getData().getCityName() + " (" + toCity.getData().getCityCode() + ") " + "with a distance of " + distance + "."); else System.out.println("The road going from " + fromCity.getData().getCityName() + " (" + fromCity.getData().getCityCode() + ") to " + toCity.getData().getCityName() + " (" + toCity.getData().getCityCode() + ") " + "could not be inserted."); } else System.out.println("One of the city codes does not exist.");

break; case "Q": System.out.print("City code: "); userInput = scanner.nextLine().toUpperCase(); Vertex city = findCityByCode(userInput); if(city != null) System.out.println(city.getData().toString()); else System.out.println("The city corresponding to city code " + userInput + " does not exist."); break; case "R": System.out.print("City codes: "); userInput = scanner.nextLine().toUpperCase(); edgeData = parseStringToStrings(userInput, "[ ]+"); fromCity = findCityByCode(edgeData.get(0)); toCity = findCityByCode(edgeData.get(1));

if(cityDigraph.removeEdge(fromCity, toCity)) System.out.println("The road from " + fromCity.getData().getCityName() + " (" + fromCity.getData().getCityCode() + ") and " + toCity.getData().getCityName() + " (" + toCity.getData().getCityCode() + ") " + " has been removed."); else System.out.println("The road going from " + fromCity.getData().getCityName() + " (" + fromCity.getData().getCityCode() + ") to " + toCity.getData().getCityName() + " (" + toCity.getData().getCityCode() + ") " + "does not exist.");

break; default: System.out.println("ERROR: " + command + " is not a valid option."); } }while(!command.equals("E")); }

/** * Finds a city from a given city code. */ public static Vertex findCityByCode(String cityCode) { for (Vertex vertex : cityDigraph.getVertices()) if(vertex.getData().getCityCode().equals(cityCode)) return vertex;

return null; }

public static Vertex findCityByNumber(int cityNumber) { for (Vertex vertex : cityDigraph.getVertices()) if(vertex.getData().getCityNumber() == cityNumber) return vertex;

return null; }

public static String readFile(String fileName, String delimiter) { // This will reference one line at a time String line;

String data = "";

try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(fileName);

// Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) { data = data + line + delimiter; }

// Always close files. bufferedReader.close(); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); }

return data; }

public static ArrayList createCities(String data) { ArrayList cities = new ArrayList<>();

ArrayList citiesStrings = parseStringToStrings(data, ",");

for(int i = 0; i < citiesStrings.size(); i++) { City city = new City(); String cityStr = citiesStrings.get(i).trim().replaceAll("[ ]{2,}", ",");

ArrayList cityString = parseStringToStrings(cityStr, ",");

for (int j = 0; j < cityString.size(); j++) { if (j == 0) city.setCityNumber(Integer.valueOf(cityString.get(j))); else if (j == 1) city.setCityCode(cityString.get(j)); else if (j == 2) city.setCityName(cityString.get(j)); else if (j == 3) city.setPopulation(Integer.valueOf(cityString.get(j))); else if (j == 4) city.setElevation(Integer.valueOf(cityString.get(j))); }

cities.add(city); }

return cities; }

public static ArrayList createRoads(String data) { ArrayList roads = new ArrayList<>();

ArrayList roadsStrings = parseStringToStrings(data, ",");

for(int i = 0; i < roadsStrings.size(); i++) { Road road = new Road(); String roadStr = roadsStrings.get(i).trim().replaceAll("[ ]{2,}", ",");

ArrayList roadString = parseStringToStrings(roadStr, ",");

for (int j = 0; j < roadString.size(); j++) { if (j == 0) road.setFromCity(Integer.valueOf(roadString.get(j))); else if (j == 1) road.setToCity(Integer.valueOf(roadString.get(j))); else if (j == 2) road.setDistance(Integer.valueOf(roadString.get(j))); }

roads.add(road); }

return roads; }

public static ArrayList parseStringToStrings(String string, String delimiter) { return new ArrayList(Arrays.asList(string.split(delimiter))); }

public static ArrayList parseStringToInteger(String string, String delimiter) { ArrayList strings = parseStringToStrings(string, delimiter); ArrayList integers = new ArrayList(strings.size());

for (String str : strings) integers.add(Integer.valueOf(str));

return integers; } } ---------------------------------------------------------------------------------------------------- City.java -------------------------------------------------- public class City { private int cityNumber; private String cityCode; public String cityName; private int population; private int elevation;

public City() { }

public City(int cityNumber, String cityCode, String cityName, int population, int elevation) { this.cityNumber = cityNumber; this.cityCode = cityCode; this.cityName = cityName; this.population = population; this.elevation = elevation; }

public int getCityNumber() { return cityNumber; }

public void setCityNumber(int cityNumber) { this.cityNumber = cityNumber; }

public String getCityCode() { return cityCode; }

public void setCityCode(String cityCode) { this.cityCode = cityCode; }

public String getCityName() { return cityName; }

public void setCityName(String cityName) { this.cityName = cityName; }

public int getPopulation() { return population; }

public void setPopulation(int population) { this.population = population; }

public int getElevation() { return elevation; }

public void setElevation(int elevation) { this.elevation = elevation; }

@Override public String toString() { return cityNumber + " " + cityCode + " " + cityName + " " + population + " " + elevation; }

public String toStringDebug() { return "City{" + "cityNumber=" + cityNumber + ", cityCode='" + cityCode + '\'' + ", cityName='" + cityName + '\'' + ", population=" + population + ", elevation=" + elevation + '}'; } } ---------------------------------------------------------------------------------------------- Digraph.java ------------------------------------------------- import java.util.ArrayList; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue;

public class Digraph { private ArrayList> vertices; private int edgeCount;

public Digraph() {

}

public Digraph(ArrayList> vertices, int edgeCount) { this.vertices = vertices; this.edgeCount = edgeCount; }

public ArrayList> getVertices() { return vertices; }

public void setVertices(ArrayList> vertices) { this.vertices = vertices; }

public int getEdgeCount() { return edgeCount; }

public boolean insertEdge(Vertex startVertex, Vertex endVertex, double weight) { if(startVertex.connect(endVertex, weight)) { edgeCount++; return true; }

return false; }

public boolean removeEdge(Vertex startVertex, Vertex endVertex) { ArrayList> edges = startVertex.getEdges();

for (int i = 0; i < edges.size(); i++) { if(edges.get(i).getVertex().equals(endVertex)) { edges.remove(i); System.out.println(edges.toString()); return true; } }

return false; }

public ArrayList> shortestDistance(Vertex startVertex, Vertex endVertex) { ArrayList> path = new ArrayList<>();

for(int i = 0; i < vertices.size(); i++) { vertices.get(i).setCost(Double.POSITIVE_INFINITY); vertices.get(i).setPreviousVertex(null); }

// Distance from source to source. startVertex.setCost(0);

//PriorityQueue PriorityQueue> vertexPriorityQueue = new PriorityQueue>(vertices.size(), costComparator); for(Vertex vertex : vertices) vertexPriorityQueue.add(vertex);

while(!vertexPriorityQueue.isEmpty()) { Vertex closestVector = vertexPriorityQueue.poll();

if(closestVector.getCost() == Double.POSITIVE_INFINITY) break;

vertexPriorityQueue.remove(closestVector);

for(Vertex neighbor : closestVector.getNeighbors()) { double costDifference = closestVector.getCost() + neighbor.getCost();

if(costDifference < neighbor.getCost()) { neighbor.setCost(costDifference); neighbor.setPreviousVertex(closestVector); path.add(closestVector); }

path.add(closestVector); } } return path; }

//Comparator anonymous class implementation private Comparator> costComparator; { costComparator = new Comparator>() { @Override public int compare(Vertex vertex, Vertex nextVertex) { return (int) (vertex.getCost() - nextVertex.getCost()); } }; }

} ----------------------------------------------------------------------------------------------------------- Edge.java ---------------------------------------- public class Edge { private Vertex vertex; private double weight;

public Edge() {

}

public Edge(Vertex vertex, double weight) { this.vertex = vertex; this.weight = weight; }

public Vertex getVertex() { return vertex; }

public void setVertex(Vertex vertex) { this.vertex = vertex; }

public double getWeight() { return weight; }

public void setWeight(double weight) { this.weight = weight; }

@Override public String toString() { return "Edge{" + "vertex=" + vertex.toString() + ", weight=" + weight + '}'; } } ------------------------------------------------------------------------------------- Road.java ------------------------------------------ public class Road { private int fromCity; private int toCity; private int distance;

public Road() {

}

public Road(int fromCity, int toCity, int distance) { this.fromCity = fromCity; this.toCity = toCity; this.distance = distance; }

public int getFromCity() { return fromCity; }

public void setFromCity(int fromCity) { this.fromCity = fromCity; }

public int getToCity() { return toCity; }

public void setToCity(int toCity) { this.toCity = toCity; }

public int getDistance() { return distance; }

public void setDistance(int distance) { this.distance = distance; }

@Override public String toString() { return "Road{" + "fromCity=" + fromCity + ", toCity=" + toCity + ", distance=" + distance + '}'; }

} ------------------------------------------------------------------------------ Vertex.java ------------------------------------- import java.util.ArrayList;

public class Vertex { private T data; private boolean isVisted = false; private ArrayList> edges; private Vertex previousVertex; private double cost;

public Vertex(T data) { this.data = data; edges = new ArrayList<>(); isVisted = false; previousVertex = null; cost = 0; }

public T getData() { return data; }

public void setData(T data) { this.data = data; }

public boolean isVisted() { return isVisted; }

public void visit() { isVisted = true; }

public void unvisit() { isVisted = false; }

public ArrayList> getEdges() { return edges; }

public Vertex getPreviousVertex() { return previousVertex; }

public void setPreviousVertex(Vertex previousVertex) { this.previousVertex = previousVertex; }

public boolean hasPreviousVertex() { if(previousVertex != null) return true; else return false; }

public double getCost() { return cost; }

public void setCost(double cost) { this.cost = cost; }

public boolean connect(Vertex endVertex, double edgeWeight) { Edge newEdge = new Edge(endVertex, edgeWeight);

if(edges.isEmpty()) { edges.add(newEdge); return true; } else { for (Edge edge : edges) { if(!edge.getVertex().equals(newEdge.getVertex())) { edges.add(newEdge); return true; } else System.out.println("This edge already exists!"); } }

return false; }

public boolean connect(Vertex endVertex) { return connect(endVertex, 0); }

public ArrayList> getNeighbors() { ArrayList> neighbors = new ArrayList>();

if(this.hasNeighbor()) { for (Edge edge : edges) neighbors.add(edge.getVertex()); }

return neighbors; }

public ArrayList getWeights() { ArrayList weights = null; return weights; }

public boolean hasNeighbor() { return !edges.isEmpty(); }

public ArrayList> getUnvisitedNeighbors() { ArrayList> unvisitedNeighbors = null; return unvisitedNeighbors; }

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!