import java.io.IOException; import java.net.URL; import java.util.Scanner; import javax.swing.JOptionPane; public class Assignment2 { private static Place[] places; public static void main(String[] args) { // read the data set readData(); // Query loop Scanner inS = new Scanner(System.in); // Open console input stream // useful query loop variables boolean more = true; // more input? String query; // query string (zip code) do { // get and parse user input // query = inS.nextLine(); query = getUserInput(); System.out.println("\nYou asked me to search for zip code: " + query); // search int result = search(places, query); if (result != -1) { System.out.println("The zip code " + query + " belongs to " + places[result]); } else { System.out.println("The zip code " + query + " does not exist."); } // does user want more? System.out.print("Do you want me to search again (Yes/No)? "); String response = inS.nextLine(); more = response.equalsIgnoreCase("yes"); } while (more); System.out.println("Good Bye!"); } // main() public static String getUserInput() { String inputStr = null; while (inputStr == null) { try { inputStr = JOptionPane.showInputDialog("Enter a zip code."); } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null, "Bad numeric string - try again", "Input Error", JOptionPane.ERROR_MESSAGE); } // catch } return inputStr; } // getUserInput() public static int search(Place[] p, String zipCode) { // Linear Search for (int i = 0; i < p.length; i++) { if (p[i].equals(zipCode)) { return i; } } return -1; } // Search() public static void readData() { try { // Create a valid web resource (URL) URL webFile = new URL("http://cs.brynmawr.edu/Courses/cs206/fall2017/DataFiles/uszipcodes.csv"); // Open the file Scanner inS = new Scanner(webFile.openStream()); String line; // Parse first line to get N line = inS.nextLine(); String[] tokens = line.split(","); int N = Integer.parseInt(tokens[0]); System.out.println("There are " + N + " entries in input file."); places = new Place[N]; // Create the array of size. N int i=0; while (inS.hasNextLine()) { line = inS.nextLine(); // Parse line... tokens = line.split(","); String town, state, zip; town = tokens[1]; state = tokens[2]; zip = tokens[0]; Place p = new Place(town, state, zip); places[i] = p; // add to dataset i = i + 1; } inS.close(); System.out.println("The dataset contains:" + places.length + " entries."); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } // readData() } // class Assignment2