Postal.java


Below is the syntax highlighted version of Postal.java from §4.4 Symbol Tables.


/******************************************************************************
 *  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) {
                StdOut.println("invalid zip code");
                continue;
            }

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


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:30:21 EDT 2022.