Coursera - Computer Science: Programming With A Purpose

Week 4: Input And Output - World Maps

Write a program WorldMap.java that reads boundary information of a country (or other geographic entity) from standard input and plots the results to standard drawing. A country consists of a set of regions (e.g., states, provinces, or other administrative divisions), each of which is described by a polygon.

Input format. The first line contains two integers: width and height. The remaining part of the input is divided into regions.

For simplicity, if a region requires more than one polygon to describe its boundary, we treat it as multiple regions, with one polygon per region.

Output format. Draw the polygons to standard drawing, using the following guidelines:

Here are some sample executions for the input files usa.txt, russia.txt, and world.txt. Additional input files are available for 100+ countries and all 50 U.S. states.

~/Desktop/io> javac WorldMap.java

~/Desktop/io> java WorldMap < usa.txt

~/Desktop/io> java WorldMap < russia.txt

~/Desktop/io> java WorldMap < world.txt

Note: the above description is copied from Coursera and converted to markdown for convenience

Solution:

public class WorldMap {

    public static void main(String[] args) {
        final int width = StdIn.readInt();
        final int height = StdIn.readInt();

        StdDraw.enableDoubleBuffering();
        StdDraw.setCanvasSize(width, height);
        StdDraw.setXscale(0, width);
        StdDraw.setYscale(0, height);
        while (!StdIn.isEmpty()) {
            StdIn.readString();
            final int vertices = StdIn.readInt();
            final double[] x = new double[vertices];
            final double[] y = new double[vertices];
            for (int i = 0; i < vertices; i++) {
                x[i] = StdIn.readDouble();
                y[i] = StdIn.readDouble();
            }
            StdDraw.polygon(x, y);
        }
        StdDraw.show();
    }
}

Link To: Java Source Code