import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { // To count the number of occurences of a, b, c... int[] count = new int[26]; String fileName = "SomeText.txt"; File file = new File(fileName); try { Scanner scan = new Scanner(file); while (scan.hasNextLine()) { String line = scan.nextLine(); countLetters(count, line); } printPercentages(count); } catch (IOException e) { System.out.println("Problem opening the file"); } } public static void countLetters(int[] count, String line) { line = line.toLowerCase(); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c >= 'a' && c <= 'z') { int index = c - 'a'; count[index]++; } } } public static void printPercentages(int[] count) { int totalLetters = 0; for (int i = 0; i < count.length; i++) { totalLetters += count[i]; } DecimalFormat df = new DecimalFormat("0.00"); for (int i = 0; i < count.length; i++) { // Math.max to guard against a division by 0 double p = 100.0 * count[i] / Math.max(totalLetters, 1); System.out.println((char) (i + 'a') + " = " + df.format(p) + "%"); } } }