ThatBoy123
ThatBoy123

Reputation: 77

Counting and Printing the Occurrence of Each Letter from a Text File

I need to print the total times each letter appears in a text file. Any thoughts on how to loop this? I've got the basics down. Not sure if I'm using the array correctly. Also, how would I go about printing it?

A sample text file:

Hello, my name is Zachary. Taking people's x-rays is what I do for a living.

Desired Output:

Letters - Frequencies in file:

a - 7

b - 0

c - 1

d - 1

e - 4

f - 1

g - 2

h - 3

i - 6

j - 0

k - 1

l - 4

m - 2

n - 3

o - 4

p - 2

q - 0

r - 2

s - 3

t - 2

u - 0

v - 1

w - 1

x - 1

y - 3

z - 1

/*
 * program that reads in a text file and counts the frequency of each letter
 * displays the frequencies in descending order
 */

import java.util.*; //needed for Scanner
import java.io.*;  //needed for File related classes
public class LetterCounter {
  public static void main(String args[]) throws IOException{
    Scanner keyboard = new Scanner(System.in); //Scanner to read in file name
    System.out.println("Enter the name of the text file to read:");
    String filename = keyboard.next();

    //This String has all the letters of the alphabet
    //You can use it to "look up" a character using alphabet.indexOf(...) to see what letter it is
    //0 would indicate 'a', 1 for 'b', and so on.  -1 would mean the character is not a letter
    String alphabet = "abcdefghijklmnopqrstuvwxyz";

    //TODO: create a way to keep track of the letter counts
    //I recommend an array of 26 int values, one for each letter, so 0 would be for 'a', 1 for 'b', etc.
    int[] myArray = new int[26];

    Scanner fileScan = new Scanner(new File(filename));  //another Scanner to open and read the file
    //loop to read file line-by-line
    while (fileScan.hasNext()) {  //this will continue to the end of the file
      String line = fileScan.nextLine();  //get the next line of text and store it in a temporary String
      line = line.toLowerCase( ); // convert to lowercase

      //TODO: count the letters in the current line
      for (int i=0; i<line.length(); i++) {
        myArray[line.charAt(i) - 'a']++; 
      }
    }
    fileScan.close(); //done with file reading...close the Scanner so the file is "closed"



    //print out frequencies
    System.out.println("Letters - Frequencies in file:");

    //TODO: print out all the letter counts


  }
}

Upvotes: 0

Views: 613

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44854

Really it is just the inverse of when you are storing

for (int i = 0; i < myArray.length; i++) {
        System.out.printf("%c has %d%n", i + 'a', myArray[i]);
}

You will also want to check that the input char is alpha

if (Character.isAlphabetic(line.charAt(i))) {
      myArray[line.charAt(i) - 'a']++;
}

This code should be to replace

for (int i=0; i<line.length(); i++) {
    myArray[line.charAt(i) - 'a']++; 
}

Upvotes: 1

Related Questions