1

The following class keeps giving me a null pointer when I try to call the addPlayer method and I have no idea what the heck I'm doing wrong. : Keep in mind this is really simple stuff...supposedly... I'm learning Java.

import java.util.*;

public class Team {

    private String teamName;
    private  ArrayList<Player> players;
    private int numberOfPlayers; 

    public Team(String teamName) {

        this.teamName = teamName;

    }

    public String getName() {

        return this.teamName;

    }

    public void addPlayer(Player player) {
        this.players.add(player);
        }


    public void printPlayers() {

        for (Player player : this.players) {
            System.out.println(player);
        }
    }
}

Here is the Player class :

public class Player {

    private String name;
    private int goals;

    public Player(String name) {
        this.name = name;
    }

    public Player(String name, int goals) {

        this.name = name;
        this.goals = goals;
    }

    @Override
    public String toString() {

        return this.getName() + ", goals " + this.goals();
    }

    public String getName () {
        return this.name; 
    }

    public int goals() {
        return this.goals; 
    }

}
1

3 Answers 3

9

This is your problem:

private  ArrayList<Player> players;

is not initialized, you never create a new one when you instantiate your class.

Add the following to your constructor:

public Team(String teamName) {

    this.teamName = teamName;
    this.players = new ArrayList<Player>();

}
Sign up to request clarification or add additional context in comments.

Comments

6

You haven't initialized the variable, thus its value is null.

private  ArrayList<Player> players = new ArrayList<Player>();

That should fix it.

1 Comment

Oh wow.... i have been mucking with this thing for 2 hours trying to get it to quit giving me null pointer.... LOL Thank you!
2

You have declared an ArrayList but where is the initialization?? Fix it by initializing the ArrayList as :

private  ArrayList<Player> players = new ArrayList<Player>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.