Histogram.java


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


/******************************************************************************
 *  Compilation:  javac Histogram.java
 *  Dependencies: Draw.java
 *
 *  This data type supports simple client code to create dynamic
 *  histograms of the frequency of occurrence of values in [0, N).
 *  The frequencies are kept in an instance-variable array, and
 *  an instance variable max tracks the maximum frequency (for scaling).
 *  This version is different from
 *  https://introcs.cs.princeton.edu/java/32class/Histogram.java.html
 *  because each histogram is drawn in its own window.
 *
 ******************************************************************************/


public class Histogram {
    private int freq[];     // freq[i] = # occurences of i
    private int N;          // data values are between 0 and N
    private int max;        // maximum number of times a value occurs
    private Draw draw;      // drawing object for histogram

    // values between 0 and N
    public Histogram(String name, int N) {
        this.N    = N;
        this.freq = new int[N+1];
        this.draw = new Draw();
        this.draw.setTitle(name);
    }
    public Histogram(int N) { this("Histogram", N); }

    // insert the point i into the histogram - it must be in [0, N) or it is
    // truncated to N
    public void addDataPoint(int i) {
        if (i < 0) i = 0;
        if (i > N) i = N;
        freq[i]++;
        if (freq[i] > max) max = freq[i];
    }

    // draw the histogram
    public void draw() {
        draw.clear();
        draw.setYscale(0, max);
        draw.setXscale(0, N);
        draw.setPenRadius(0.5 / N);
        for (int i = 0; i <= N; i++) {
            draw.line(i, 0, i, freq[i]);
        }
        draw.show(0);
    }
}


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