I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.
import java.util.ArrayList; public class Ballot { private ArrayList<Candidate> ballot; private String officeName; public Ballot(String officeName) { this.officeName = officeName; ArrayList<Candidate> ballot = new ArrayList<Candidate>(); } public String getOfficeName() { return officeName; } public void addCandidate(Candidate c) { ballot.add(c); } public ArrayList<Candidate> getCandidates() { return ballot; } public static void main(String[] args) { Ballot b = new Ballot("Election"); b.addCandidate(new Candidate("Sarah", "President")); System.out.println(b); } } When I try to run the document, it throws a NullPointerException. What am I doing wrong?
ballotArrayList field. You declare a localballotvariable in your constructor and you initialise that.