john smith john smith - 1 year ago 75
Java Question

Letter count from a text file in Java

I have a Java class that imports a text file called

and I've imported it into Java and I'm wondering how I'd see how many times each letter appears. The text file contains
Hello World
so it would be like

D is shown 1 time
E is shown 1 time
H is shown 1 time
L is shown 3 times
O is shown 2 times
R is shown 1 time
W is shown 1 time



import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.applet.Main;

public class SecureTradingPractical {

public static void main(String[] args) {

try {

Scanner in = new Scanner(new FileReader("example.txt"));
while(in.hasNext()) {


} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);


I'd make use of Character.toUpper(), Character.isLetter() utility methods, and use a Map to store the counts of each character encountered, this avoids any error prone shifting of characters back to integers for array storage...

public static void main(String[] args) throws IOException {
    try (Scanner in = new Scanner(new FileReader("example.txt"))) {
        while (in.hasNext()) {

private static void letterFrequency(String input) {
    Map<Character, Integer> counts = new HashMap<>();
    for (char each : input.toCharArray()) {
        if (Character.isLetter(each)) {
            char upper = Character.toUpperCase(each);
            counts.put(upper, counts.getOrDefault(upper, 0) + 1);
    for (Entry<Character, Integer> entry : counts.entrySet()) {
        System.out.println(String.format(String.format("%s is shown %d time%s", entry.getKey(), entry.getValue(),
                entry.getValue() > 1 ? "s" : "")));