Search code examples
javaarraylistnullpointerexceptionfileinputstream

Java - NullPointerException scanning into LinkedList from Text File


I have the following class BallotPaper, which records a set of votes in a LinkedList:

import java.util.LinkedList;

public class BallotPaper {

    private LinkedList<String> votes;

    public BallotPaper() {

    }

    public void addVote(String candidateName) {
        votes.add(candidateName);
    }

    public LinkedList<String> getVotes() {
        return votes;
    }

}

I have a text file which contains a list of votes, which looks like the following:

John Jack James Fred
John Jack James Fred
Fred Jack John James
Fred Jack John James
Jack John James Fred

In my main class, I have an ArrayList of BallotPaper objects. Each line in the text file compromises of four names, which each need to be added to a single BallotPaper object, then stored in the ArrayList. Here is my code to read the text file:

private ArrayList<BallotPaper> votes = new ArrayList<>();

public void readTextFile(String fileLocation) throws FileNotFoundException {
    FileInputStream fileIn = new FileInputStream(fileLocation);
    Scanner scanner = new Scanner(fileIn);

    while(scanner.hasNextLine()) {
        votes.add(new BallotPaper());
        for(int i=0; i<4; i++) {
            String name = scanner.next().trim();
            if(!name.equals("")) {
                votes.get(votes.size() - 1).addVote(name);
            }
        }
    }
}

So my goal is for the ArrayList to contain 5 elements, each of which are BallotPaper objects with 4 entries in their respective LinkedList. I am currently getting the following error:

Exception in thread "main" java.lang.NullPointerException
    at BallotPaper.addVote(BallotPaper.java:12)
    at Model.readTextFile(AVSModel.java:50)

Solution

  • You have not itialized your votes list. Change line

     private LinkedList<String> votes;
    

    to

     private LinkedList<String> votes = new LinkedList<String>();