Region.java


Below is the syntax highlighted version of Region.java from §3.5 Inheritance.


/*************************************************************************
 *  Compilation:  javac Region.java
 *  Execution:    java Region < inputfile.txt
 *
 *  Implementation of an immutable Region ADT.
 *
 *  % java Region < USA.txt
 *
 *  % java Region < 51stbna/CA.txt
 * 
 *  % cat 51stbna/[A-Z][A-Z].txt | java Region
 *
 *************************************************************************/

public class Region {
    private final String name;
    private final String usps;
    private final Polygon polygon;

    // constructor that initializes the instance variables
    public Region(String name, String usps, Polygon polygon) {
        this.name  = name;
        this.usps  = usps;
        this.polygon  = polygon;
    }

    public String toString() {
        // return usps + " " + name + "\n" + polygon;
        return name + ", " + usps;
    }

    public void draw() { polygon.draw(); }
    public void fill() { polygon.fill(); }

    public boolean contains(Point p) {
        return polygon.contains(p);
    }



    public static void main(String[] args) {

        // year of election, read from command-line
        int year = Integer.parseInt(args[0]);

        // input stream
        In in = new In();

        // scale coordinates
        double xmin = in.readDouble();
        double ymin = in.readDouble();
        double xmax = in.readDouble();
        double ymax = in.readDouble();
        in.readLine();        
        in.readLine();        


        // set window size
        double ratio = 1.4;      // a guess
        int WIDTH = 1200;
        int HEIGHT  = (int) ((ymax - ymin) / (xmax - xmin) * ratio * WIDTH);
        if (HEIGHT >= 800) { WIDTH = WIDTH * 800 / HEIGHT; HEIGHT = 800; }
        StdDraw.setCanvasSize(WIDTH, HEIGHT);
        StdDraw.setXscale(xmin, xmax);
        StdDraw.setYscale(ymin, ymax);


        // process data
        while (!in.isEmpty()) {
            String name = in.readLine();
            String usps = in.readLine();
            System.out.println(name + ", " + usps);
            Polygon polygon = new Polygon(in);
            Region region = new Region(name, usps, polygon);
            VoteTally votes = new VoteTally(name, usps, year);
            StdDraw.setPenColor(votes.purple());
            region.fill();

            // eat up rest of line
            in.readLine();
        }

    }

}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.