John A.
Implement two classes and use an array of objects to count the number of times each letter occurs in a text file.
Counter - each counter should maintain a single count (don't allocate an array here)
Counter() - constructor that initializes the count to 0
void incrementCount() - increases the count by 1
void resetCount() - sets the count to 0
String toString() - returns a String representation of the count (e.g., "13")
boolean equals(Counter c) - returns true if both Counters store the same count
You will use the Counter class in a separate class called LetterInventory, which has the following methods:
LetterInventory - stores the count for all 26 letters
LetterInventory() - constructs the inventory (an array of 26 Counter objects)
void countOccurrences(Scanner file) - counts the frequency of each letter in a file
void displayTable() - displays the frequencies of each letter in the inventory
void resetInventory() - resets all of the counts to 0
Your LetterInventory class must use an array of Counter objects. Note that there is no nextChar method in the Scanner class. You must use the next() method and then use a loop through the characters of the token that is returned. Ignore any character that is not a letter. You should also treat 'a' and 'A' as the same letter.
To convert a letter into an integer index, subtract 'a' or 'A' from it. The expression (letter - 'a') will yield an integer between 0 and 25 for any lowercase letter. Should output:
a: xx
b: xx
c: xx
d: xx
ect..
Drive Code:
import java.util.Scanner;
import java.io.File;
public class LetterCounter {
public final static String filename = "testFile.txt";
// Driver to test LetterInventory class
public static void main(String[] args) {
Scanner inputFile = null;
try {
inputFile = new Scanner(new File(filename));
} catch (Exception e) {
System.out.println("File could not be opened: " + filename);
System.exit(0);
}
LetterInventory inventory = new LetterInventory();
inventory.countOccurrences(inputFile);
inventory.displayTable();
inventory.resetInventory();
}
}