Clock.java


Below is the syntax highlighted version of Clock.java from §2.4 Input and Output.


/*************************************************************************
 *  Compilation:  javac Clock.java
 *  Execution:    java Clock
 *  Dependencies: StdDraw.java
 *
 *************************************************************************/

import java.awt.Color;

public class Clock { 

    public static void main(String[] args) { 
        int SIZE = 400;
        StdDraw.create(SIZE, SIZE);
        double seconds, minutes, hours;

        // make default orientation 12 'o clock
        StdDraw.rotate(90);

        for (int t = 0; true; t++) {

            // yes, mod with doubles so all hands move every second
            seconds = t % 60;
            minutes = (t / 60.0) % 60;
            hours   = (t / 3600.0) % 12;

            StdDraw.clear(Color.lightGray);

            // clock face
            StdDraw.clear(Color.lightGray);
            StdDraw.setColor(Color.black);
            StdDraw.go(SIZE/2, SIZE/2);
            StdDraw.spot(0.9 * SIZE);

            // hour markers
            for (int i = 0; i < 12; i++) {
                StdDraw.go(SIZE/2, SIZE/2);
                StdDraw.rotate(i * 30);
                StdDraw.setColor(Color.black);
                StdDraw.goForward(0.4 * SIZE);
                StdDraw.setColor(Color.blue);
                StdDraw.spot(7);
                StdDraw.rotate(-i * 30);
            }

            // second hand
            StdDraw.setColor(Color.yellow);
            StdDraw.go(SIZE/2, SIZE/2);
            StdDraw.rotate(-6 * seconds);
            StdDraw.penDown();
            StdDraw.goForward(0.35 * SIZE);
            StdDraw.penUp();
            StdDraw.rotate(6 * seconds);

            // minute hand
            StdDraw.setColor(Color.gray);
            StdDraw.go(SIZE/2, SIZE/2);
            StdDraw.rotate(-6 * minutes);
            StdDraw.penDown();
            StdDraw.goForward(0.3 * SIZE);
            StdDraw.penUp();
            StdDraw.rotate(6 * minutes);

            // hour hand
            StdDraw.setColor(Color.white);
            StdDraw.go(SIZE/2, SIZE/2);
            StdDraw.rotate(-30 * hours);
            StdDraw.penDown();
            StdDraw.goForward(0.25 * SIZE);
            StdDraw.penUp();
            StdDraw.rotate(30 * hours);

            // 1000 miliseconds = 1 second
            StdDraw.pause(1000);
        }
    }

}


Last updated: Sun Oct 24 22:26:04 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.