-5

I need to create a program that will read in the contents of a .TXT file and output how many As’ (either A or a) that are present within the file.

Task: Start by downloading and importing the 7B_Batch.txt file into your project. Create a program that will read in the contents of this file and output how many As’ (either A or a) that are present within the file. There are a total of 250 lines in the file.

The file has these letters:

X
j
9
p
Q
0
n
v
[etc...]

And my code so far has been:

import java.io.*;
import java.util.*;
public class lettercount {

    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader ("7B_Batch.txt"); 
         //connecting to file (7aname) by adding a file reader 
         BufferedReader br = new BufferedReader (fr); 
         //adding buffered reader which connects to the File Reader
         int total = 0;
         String line = br.readLine();
         char find = 'A';
         for ( int i = 0; i < 250; i++)
                 {
                    line = br.readLine();
                    if (line.equals(find))
                            {
                                total = total+1;
                            }
                 }
         System.out.println("Counting the As' in the file....");
         System.out.println("I found "+total +" As' in the file!");
    }

}

The issue is that the line if (line.equals(find)) throws a NullPointerException:

Exception in thread "main" java.lang.NullPointerException at lettercount.main(lettercount.java:16)

Kevin J. Chase
  • 3,856
  • 4
  • 21
  • 43
  • 1
    You want to use streams to read. Then just run through your data matching what you want to find, then increment a counter when you find an instance of the data you seek. –  Mar 12 '17 at 22:33
  • 2
    See how to ask homework questions https://meta.stackoverflow.com/q/334822/101087 – NineBerry Mar 12 '17 at 22:33
  • Folks, please don't up-vote homework type questions that show no evidence of initiative or effort. We shouldn't be encouraging this sort of thing. If they improve their question, yes, **then** up-vote it, but not in this state. – Hovercraft Full Of Eels Mar 12 '17 at 22:37
  • 1
    We can not help you if you don't put any effort into it. Please tell us what you've tried, and what problems you are encountering. – Thomas Mar 12 '17 at 22:44
  • ^---- Sorry, I'm new to this - I have posted the attempt I made and the issue is that in the line: if (line.equals(find)) it says: Exception in thread "main" java.lang.NullPointerException at lettercount.main(lettercount.java:16) – Manraj Sandhu Mar 12 '17 at 22:53
  • 1
    The heuristic for debugging a NullPointerException is almost always the same: You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. In the future, please search on the subject before posting, since this is too common a problem to post yet another NPE question. – Hovercraft Full Of Eels Mar 12 '17 at 22:55
  • 1
    Please check out the decent answers to be found in [this similar question](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Hovercraft Full Of Eels Mar 12 '17 at 22:55
  • So study the line `lettercount.java:16` as indicated in your NPE stacktrace -- what variables are used on that line? Which are null? Find out. – Hovercraft Full Of Eels Mar 12 '17 at 22:56
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Kevin J. Chase Mar 13 '17 at 01:49

3 Answers3

1

You use br.readLine() before the loop, assigning it to the variable line. But you don't use that value because you overwrite this value at the beginning of the loop.

This way, you try to read lines of the file 251 times, although the loop runs 250 times. When trying to read the 251st line, there is none in the file and br.readLine() returns null.

Remove the call to br.readLine() when declaring the variable line.

An additional improvement would be to replace the for-loop with a while-loop that runs until br.readLine() returns null. This way, you don't have to know how many lines there are in the file beforehand.

NineBerry
  • 26,306
  • 3
  • 62
  • 93
0
  • You definitely need to check if line you've got from buffered reader is not null.
  • I think you have one additional read, which you don't need - before the loop you take the line, when you define the variable. That might lead to an NPE inside the loop.
  • I believe it doesn't make much sense to check whether String is equal to char as the result is always false.
  • According to the task you have to check both 'a' and 'A'.

Here is how I would solve this with java 8 streams, just replace ByteArrayInputStream with FileInputStream or create FileReader in-place.

    ByteArrayInputStream in = new ByteArrayInputStream("a\nA\nb\nc\na\nd\n".getBytes());
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        long count = reader.lines()
                .filter(letter -> letter.compareToIgnoreCase("a") == 0)
                .count();
        System.out.println("There are " + count + " a's in the file");
    }

Hope, this helps.

evgenii
  • 1,190
  • 1
  • 8
  • 21
0

Well in order to avoid the null br.redLine() will get you a null when there are no more words so use a while for that, and in order to count what you need you can use Regex, Look this code I made hope it helps you (If you use Java 7 the code will be simpler), and i used a counter int so i know how manny aA are in the file

private static final String FILENAME = "/Users/jucepho/Desktop/ansi.txt";

   public static void main(String[] args) {
            BufferedReader br = null;
            FileReader fr = null;
             String pattern = "[aA]";
              Pattern r = Pattern.compile(pattern);
              int counter=0;
            try {
                fr = new FileReader(FILENAME);
                br = new BufferedReader(fr);
                String sCurrentLine;
                br = new BufferedReader(new FileReader(FILENAME));
                while ((sCurrentLine = br.readLine()) != null) {
                    //System.out.println(sCurrentLine);
                    Matcher m = r.matcher(sCurrentLine);
                     if (m.find( )) {
                         System.out.println(m.group());
                         counter++;
                     }

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)
                        br.close();
                    if (fr != null)
                        fr.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("There are :"+counter +" words");
        }

It gives me as Result:

There are :218 words

Yussef
  • 610
  • 6
  • 11