// CSE 142, Summer 2008, Helene Martin // Reads a file of student midterm scores and // displays the score counts as a histogram. // This main is a great summary of the program's behavior. import java.util.*; import java.io.*; import java.awt.*; public class Histogram { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("midterm_scores.txt")); int[] scores = tallyScores(input); consoleHistogram(scores); drawHistogram(scores); } // Counts how many people got each score and returns an array // containing the counts. public static int[] tallyScores(Scanner input) { int[] scores = new int[102]; // scores range from 0 to 101 while(input.hasNextInt()) { int score = input.nextInt(); scores[score]++; } return scores; } // Outputs an ASCII histogram to the console. public static void consoleHistogram(int[] scores) { for(int i = 0; i < scores.length; i++){ System.out.print(i + ": "); // print a * for each person who got a score of i for(int j = 0; j < scores[i]; j++) { System.out.print("*"); } System.out.println(); } } // Draws a histogram on a DrawingPanel. public static void drawHistogram(int[] scores) { DrawingPanel p = new DrawingPanel(scores.length * 3, 100); Graphics g = p.getGraphics(); for(int i = 0; i < scores.length; i++) { g.drawLine(i * 3 + 3, 100, i * 3 + 3, 100 - scores[i] * 10); } } }