William White William White - 16 days ago 5
Java Question

Letter Frequency Program in Java

I am trying to code a letter frequency program that counts the alphabetic characters from a .txt file and presents the frequency data in a 2 column table. I cannot figure out how to call the function

printChars
from the display function. I am also stuck on printing the frequency data out in the
printChars
function. Anyone have any advice? Thanks.

Here is my code:

final static int AlphabetSize = 26;
final static Scanner cin = new Scanner(System.in);
final static PrintStream cout = System.out;
final static int MaxBarLength = 50;

public static void main(String[] args) {
String fileName;




// get the file name
cout.print("Enter the file name: ");
fileName = cin.nextLine();

// process the file
try {
processFile(fileName);
}
catch (IOException e) {
e.printStackTrace();
} // end try



} // end main

static void processFile(final String fileName)
throws FileNotFoundException, IOException
{
FileInputStream inFile = new FileInputStream(fileName);
int inputValue;

// declare other variables you need
int counters [] = new int [26];

// get the first character from file
inputValue = inFile.read();
while (inputValue != -1) {
char ch = (char) inputValue;

// add code to process this character
if (ch >= 'a' && ch <= 'z'){
counters[ch - 'a']++;
}

// read next input character
inputValue = inFile.read();
} // end loop

inFile.close();

// generate appropriate output
display(counters);

} // end function

static void display(final int [] counters) {
// write code for this function

System.out.println("Letter" + " " + "Count");
System.out.println("------" + " " + "-----");
printChars(n, c);
} // end function

// char2int is complete
static int char2int(final char arg) {
if (!Character.isLetter(arg))
return -1;
else
return (int) Character.toUpperCase(arg) - (int) 'A';
} // end function


// function printChars writes n copies of the character c to the
// standard output device
static void printChars (final int n, final char c) {
// write the code
for (int i = 0; i < 26; i++){
System.out.printf("%c%7d\n", i + 'A', counters[i]);
}

}

// end printChars

Answer

You need to change the signature of printChars to take the array of counters:

static void printChars (final int[] counters) {
    for (int i = 0; i < 26; i++){
       System.out.printf("%c%7d\n", i + 'A', counters[i]);
   }
}

Now you can call it the usual way:

printChars(counters);

Demo.