import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import javax.swing.JOptionPane;
public class Assignment3 {
static Place[] places; // the "database' of Place objects
public static void main(String[] args) {
// input the zip code database readData(); System.out.println("Done reading data. Found " + places.length + " entries.");
// Search String[] options = { "Do it again?", "Exit" }; int response = 0; String answer; do { String zip = JOptionPane.showInputDialog("Enter a Zip Code.");
if (zip != null) { // Search System.out.println("You asked me to search for Zip Code: " + zip); int r = search(zip, places); if (r>=0) { answer = "The Zip Code " + zip + " belongs to " + places[r]; } else { answer = "The Zip Code " + zip + " was not found."; } // output results System.out.println(answer); response = JOptionPane.showOptionDialog(null, answer, "Results...", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, // do not use a custom icon options, // the titles of buttons options[0]); // default button title } } while (response == 0); System.out.println("\nGood Bye!"); } // main()
public static int search(String zip, Place[] p) { // Searches for zip in the database, p. Brute force sequential search for (int i=0; i < p.length; i++) { if (p[i].equals(zip)) { return i; // found at i! } } return -1; // not found } // search() public static void readData() { // Read the zip code data file String inputFileName = "Data/testZips.txt"; int N=0; try { Scanner input = new Scanner(new File(inputFileName));
if (input.hasNextLine()) { // read and parse first line of data file String line = input.nextLine(); String[] linePieces = line.split("[, ]"); // Extract the number of entries in this data file, N N = Integer.parseInt(linePieces[1]); } // Next, read the entire data file places = new Place[N]; int i=0; while (input.hasNextLine()) { String line = input.nextLine(); // Parse the line into its pieces and store in the database String linePieces[] = line.split("\t"); String[] names = linePieces[3].split(", "); places[i] = new Place(linePieces[0], names[0], names[1]); i += 1; } input.close(); } catch (FileNotFoundException e) { System.out.println("error in opening file: " + inputFileName); e.printStackTrace(); }
} // readData()
} // class Assignment3