import java.awt.Color; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; import uwcse.graphics.GWindow; import uwcse.graphics.Rectangle; import uwcse.graphics.TextShape; public class FileInput { /** * Reading from a file */ public static void main(String[] args) { // character counters int[] count = new int[26]; // use the Scanner class try { Scanner scan = new Scanner(new File("input.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); line = line.toUpperCase(); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c >= 'A' && c <= 'Z') { count[c - 'A']++; } } } System.out.println(Arrays.toString(count)); // display the histogram histogram(count); } catch (IOException e) { } } /** * Displays the letter frequencies as an histogram */ public static void histogram(int[] count) { GWindow w = new GWindow(); int width = w.getWindowWidth() / 26 - 4; // maximum value in count int max = count[0]; for (int i = 1; i < count.length; i++) { if (max < count[i]) { max = count[i]; } } int maxHeight = w.getWindowHeight() - 15; // save 15 pixels to display the character int x = 2, y = maxHeight; // bottom left corner of a bar for (int i = 0; i < count.length; i++) { // height of the bar int h = (count[i] * maxHeight) / max; Rectangle r = new Rectangle(x, y - h, width, h, Color.BLUE, true); w.add(r); // display the character below the bar String s = (char) (i + 'A') + ""; TextShape t = new TextShape(s, x + width / 3, y ); w.add(t); // next bar x += width + 4; } } }