CSE142 Program Example handout #21 Program file Histogram.java --------------------------- // Stuart Reges // 2/18/05 // // This program reads an input file of test scores (integers) and displays a // histogram of the score distribution. import java.io.*; import java.awt.*; import java.util.*; public class Histogram { public static final int MAX_SCORE = 100; // max possible score public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("histogram.txt")); // read file into count array int[] count = new int[MAX_SCORE + 1]; while (input.hasNextInt()) { count[input.nextInt()]++; } // use array to produce a histogram for (int i = 0; i < count.length; i++) { if (count[i] != 0) { System.out.print(i + ": "); for (int j = 1; j <= count[i]; j++) { System.out.print("*"); } System.out.println(); } } draw(count); } // Uses a DrawingPanel to draw the histogram public static void draw(int[] count) { DrawingPanel p = new DrawingPanel(count.length * 3 + 6, 200); Graphics g = p.getGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < count.length; i++) { g.drawLine(i * 3 + 3, 175, i * 3 + 3, 175 - 5 * count[i]); } } } Histogram output ---------------- 19: * 30: * 31: * 32: * 35: ** 40: ** 42: * 43: * 44: * 46: * 47: * 50: *** 51: ** 52: * 53: ** 54: *** 55: *** 56: ** 57: ** 58: ***** 59: * 60: ***** 61: *** 62: * 63: *** 64: ****** 65: **** 66: **** 67: *** 68: ***** 69: ******* 70: ** 71: *********** 72: *********** 73: ************ 74: ****** 75: ********** 76: ************* 77: ************** 78: ******** 79: *************** 80: ************* 81: *********** 82: ************ 83: *********** 84: ********************** 85: *************************** 86: ******************** 87: ******************************** 88: *************** 89: **************** 90: *************** 91: ********* 92: ********** 93: *********** 94: ************ 95: *********** 96: ** 97: ******* 98: ** 99: * 100: *****
Stuart Reges
Last modified: Wed Nov 16 09:10:02 PST 2005