CSE142 Program Example handout #21 Program file Histogram.java --------------------------- // Stuart Reges // 11/10/04 // // This program reads an input file of test scores (integers) and displays a // histogram of the score distribution. import java.io.*; public class Histogram { public static final int MAX_SCORE = 101; // max possible score public static void main(String[] args) { System.out.println("This program reads a file of exam scores and"); System.out.println("displays the scores in a histogram."); System.out.println(); // open file Scanner console = new Scanner(System.in); Scanner input = getInput(console); // 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(); } } // prompts the user for a file name and reads the result using the // console Scanner until the user gives a legal file name public static Scanner getInput(Scanner console) { Scanner result = null; while (result == null) { System.out.print("What is the name of the input file? "); String name = console.nextLine(); try { result = new Scanner(new File(name)); } catch (FileNotFoundException e) { System.out.println("File not found. Please try again."); } } System.out.println(); return result; } } Histogram output ---------------- 17: * 19: * 25: ** 26: * 30: * 31: * 32: * 37: * 38: * 39: * 40: * 42: * 43: * 44: * 46: **** 47: ** 48: *** 49: **** 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: ****** 101: **********
Stuart Reges
Last modified: Wed Nov 10 13:06:16 PST 2004