Mileage Between Cities in Java

Mileage Between Cities in Java Homework Sample

The program should read in a list of cities and the distances between them. The data should be stored in a 2 dimensional array, and then you should ask the user for 2 cities and display the distance between them. For more Java programming assignments contact us for a quote.

Solution:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Mileage {
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame();
String dataFile = JOptionPane.showInputDialog(frame, “Enter the name of the data file.”);
String dataFilePath = System.getProperty(“user.dir”) + “\\” + dataFile;
Scanner scanner = new Scanner(new File(dataFilePath));
// name stores name of the state/country
String name = scanner.nextLine();
// number stores number of cities
int number = scanner.nextInt();

// ArrayList to store cities
ArrayList<String> listOfCities = new ArrayList<>();
// 2d array to store mileages
int[][] mileage = new int[number][number];

// populating the array mileage by processing the file
for (int i = 0; i < number; i++) {
scanner.nextLine();
listOfCities.add(scanner.nextLine());
System.out.println(listOfCities.get(i));
for (int j = 0; j < number; j++) {
mileage[i][j] = scanner.nextInt();
}
}
scanner.close();

String input = “”;
String resultOfPreviousAction = “”;
String enumeratedListOfCities = name + ” Cities:\n\n”;
for (int i = 1; i <= number; i++) {
enumeratedListOfCities += i + “. ” + listOfCities.get(i – 1) + “\n”;
}
enumeratedListOfCities += “\nEnter from and to cities for mileage, \”Quit\”, or \”quit\” to quit.”;

while (!input.equalsIgnoreCase(“quit”)) {
input = JOptionPane.showInputDialog(frame, resultOfPreviousAction + enumeratedListOfCities);
try {
scanner = new Scanner(input);
int i = scanner.nextInt();
int j = scanner.nextInt();
scanner.close();

if(i < 1 || i > number || j < 1 || j > number) {
resultOfPreviousAction = “Invalid values, try again.\n\n”;
} else {
resultOfPreviousAction = “The distance between ” + listOfCities.get(i – 1)
+ ” and ” + listOfCities.get(j – 1) + ” is ”
+ mileage[i – 1][j – 1] + ” miles.\n\n”;
}
} catch (Exception e) {
resultOfPreviousAction = “Invalid input.\n\n”;
}
}
}
}