
Mehran Sahami Handout #41A
CS 106A November 28, 2007
Solution to Section #8
Parts of this handout by Brandon Burr and Patrick Youn g
/*
* FlightPlanner.java
* ------------------
* Reads in a file of cities and their corresponding flights,
* and allows the user to plan a flight route.
*/
import acm.program.*;
import acm.util.*;
import java.io.*;
import java.util.*;
public class FlightPlanner extends ConsoleProgram {
/** Runs the program. */
public void run() {
println("Welcome to Flight Planner!");
readFlightData("flights.txt");
println("Here's a list of all the cities in our database:");
printCityList(cities);
println("Let's plan a round-trip route!");
String startCity = readLine("Enter the starting city: ");
ArrayList<String> route = new ArrayList<String>();
route.add(startCity);
String currentCity = startCity;
while (true) {
String nextCity = getNextCity(currentCity);
route.add(nextCity);
if (nextCity.equals(startCity)) break;
currentCity = nextCity;
}
printRoute(route);
}
/** Ask user for the name of the next city in the route */
private String getNextCity(String city) {
ArrayList<String> destinations = getDestinations(city);
String nextCity = null;
while (true) {
println("From " + city + " you can fly directly to:");
printCityList(destinations);
String prompt = "Where do you want to go from " + city + "? ";
nextCity = readLine(prompt);
if (destinations.contains(nextCity)) break;
println("You can't get to that city by a direct flight.");
}
return nextCity;
}