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; 
    }

}
Frement
  • 756
  • 5
  • 10
user3690146
  • 106
  • 2
  • 8
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) –  Jun 23 '14 at 18:12

3 Answers3

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>();

}
Ryan J
  • 8,275
  • 3
  • 25
  • 28
6

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

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

That should fix it.

Frement
  • 756
  • 5
  • 10
  • 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! – user3690146 Jun 23 '14 at 18:07
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>();
SparkOn
  • 8,806
  • 4
  • 29
  • 34