DrinkingRibena
DrinkingRibena

Reputation: 1

Analysing text that is read from a file in Java

I am writing a program that analyses text that is input and calculates the average letter count. I have it working for when text is entered by the user, but I cannot get it to work for when the text is read from a file.

public static void ReadFromFile() throws IOException  {
String filename = "name.txt";
String str = new String(new char[100]);
try{
    FileReader fr = new FileReader(filename);
    BufferedReader br = new BufferedReader(fr);

    while ((str = br.readLine()) !=null) {
    System.out.println(str + "\n");
    }
    br.close();
    } catch(IOException e) {
        System.out.println("File not found");
    }
while (c != str.length()) {
    if (str.charAt(c) >= 'a' && str.charAt(c) <= 'z') {
        count[str.charAt(c) - 'a']++;   
    }
    c++;
}
for (c = 0; c<26;c++){
    if (count[c] !=0){
        double num = count[c];
        double denom = str.length();
        double average = num / denom;
        System.out.print((char) (c + 'a') + " occurs " + count[c] + " times in the entered string. Average is ");
        System.out.println(average);
    }}}}

I keep getting an error that says

Exception in thread "main" java.lang.NullPointerException
at MainMenu.ReadFromFile(MainMenu.java:79)
at MainMenu.main(MainMenu.java:25)

Any help would be greatly appreciated Thanks

Upvotes: 0

Views: 59

Answers (2)

azurefrog
azurefrog

Reputation: 10945

Earlier in your code, you have this loop:

while ((str = br.readLine()) != null) {
    System.out.println(str + "\n");
}

This will read lines from your file while str is not null.
That means that when it stops, str is null.

Since you don't give str a non-null value after that, you get an NPE when you try to run methods on str later in the code:

while (c != str.length()) {  // str is null here!
    if (str.charAt(c) >= 'a' && str.charAt(c) <= 'z') {
        count[str.charAt(c) - 'a']++;
    }
    c++;
}

My guess from looking at your code is that you want to collect information about each line in the file. To do this, instead of just printing each line, move your counting logic inside the loop which is reading the file:

// read each line from the file
while ((str = br.readLine()) != null) {
    System.out.println(str + "\n");

    // collect character data for this line
    while (c != str.length()) {
        if (str.charAt(c) >= 'a' && str.charAt(c) <= 'z') {
            count[str.charAt(c) - 'a']++;
        }
        c++;
    }
}

Then process the count array later in the code as you are already doing.

Upvotes: 0

satnam
satnam

Reputation: 11474

You are reading the entire file in, line by line and printing it to System.out

After you have finished that, you then try to process the data, but you've already finished reading in the file, hence str is 'null' and your program dies.

Upvotes: 2

Related Questions