john smith john smith - 7 months ago 31
Java Question

Letter count from a text file in Java

I have a Java class that imports a text file called

abc.txt
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


EDIT

Code

import java.io.FileNotFoundException;
import java.io.FileReader;
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()) {

System.out.println(in.next());
}

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

Answer

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()) {
            letterFrequency(in.next());
        }
    }
}

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" : "")));
    }
}
Comments