Reputation: 61
My text input file has already been processed and only contains letters (a-z) and spaces. For some reason, when I input a very large text file (about 400 000 word file,as determined via cutting and pasting into MSWord), the relative frequency count fails. but for smaller files it works e.g total character=36. Please can someone tell me where the code is going wrong?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class SoloCount {
public static void main(String[] args) throws IOException {
String inputFile = "sampleOutput.txt";
// My array for the a-z (97-122, based on ASCII table )
try {
int[] myArray = new int[26];
BufferedReader readerObject = new BufferedReader(new FileReader(inputFile));
String sCurrentLine="";
sCurrentLine = readerObject.readLine();
for(int i = 0; i<sCurrentLine.length(); i++) // for each character in the readline from the input file, a-z will be counted.
{
if (Character.isLetter(sCurrentLine.charAt(i)) == true) // qualifies characterisa letter and not an empty space.
{
char singleLetter = sCurrentLine.charAt(i);
myArray[(int)(singleLetter)-97] = myArray[(int)(singleLetter)-97] + 1; // Assigning frequency of a character. 97-122 represents a-z (ASCII table). e.g lowercase c = 97
}
}
readerObject.close();
//Calculate the total number of characters from the input file.
double sumOfCharacters= 0;
for (int i = 0; i < myArray.length; i++)
{
sumOfCharacters += myArray[i];
}
System.out.println("The total number of characters in this file is: " + sumOfCharacters);
//Calculating the realtive frequency. Divide each occurrence for each letter (a-z) by the sumOfCharacters.
System.out.printf("%10s%6s%n", "Letter", "%"); //column labels "Letter" and "%"
System.out.println();
for (int i = 0; i < myArray.length; i++)
{
char singleLetter = (char)(i + 97); //converting the decimal ASCII annotation to letters for a-z
double value = myArray[i];
System.out.printf("%8s%13f%n",singleLetter,(value/sumOfCharacters)*100);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 2881
Reputation: 323
You are reading only one line of your file - it could be that there are only 36 characters on the line or there is a newline character after 36 characters.
You can also increase the buffer size of your BufferedReader by passing in a larger initial buffer size -
BufferedReader readerObject = new BufferedReader(new FileReader(inputFile), 2048);
For more details please see here.
Upvotes: 1