Postal.java


Below is the syntax highlighted version of Postal.java.


/*************************************************************************
 *  Compilation:  javac Postal.java
 *  Execution:    java Postal zipcodefile.txt
 *
 *  % java Postal zips.txt
 *  08540 14853
 *  172.367 miles from
 *  PRINCETON_NJ (40.366633, 74.640832) to ITHACA_NY (42.443087, 76.488707)
 *
 *  08540 19072
 *  40.558 miles from
 *  PRINCETON_NJ (40.366633, 74.640832) to NARBERTH_PA (40.01768, 75.2594)
 *
 *************************************************************************/

public class Postal { 

    public static void main(String[] args) {

        // read ZIP code and location from a file and store in a symbol
        // table with key = ZIP code, value = Location
        In in = new In(args[0]);
        ST<String, Location> st = new ST<String, Location>();
        while (!in.isEmpty()) {
            String zip       = in.readString();
            String name      = in.readString();
            double latitude  = in.readDouble();
            double longitude = in.readDouble();
            Location loc = new Location(name, latitude, longitude);
            st.put(zip, loc);
        }

        // read in pairs of ZIP codes from standard input and output
        // the great-circle distance between them
        while (!StdIn.isEmpty()) {

            // read pairs of ZIP codes and get corresponding locations
            String zip1 = StdIn.readString();
            String zip2 = StdIn.readString();
            Location loc1 = st.get(zip1);
            Location loc2 = st.get(zip2);

            // one (or both) ZIP codes are not in file
            if (loc1 == null || loc2 == null) {
                System.out.println("invalid zip code");
                continue;
            }

            // output results
            double distance = loc1.distanceTo(loc2);
            System.out.printf("%6.3f miles from\n", distance);
            System.out.println(loc1 + " to " + loc2);
        }
    }
}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Fri May 1 07:16:38 EDT 2009.