-3

I have a public class called Tournament which has a nested private static class called Team.

public class Tournament {

    private Team[] teams;
    private static int noOfTeams;
    private  Queue<Team> queue = new LinkedList<>();
    Team teamA,teamB,winner;


    public Tournament(int noOfTeams) 
    {
        this.noOfTeams = noOfTeams;     
        generateTeams();
    }


    private void generateTeams()    
    {


        for (int i = 0; i < noOfTeams; i++) 
        {       
            this.teams[i] = new Team();  // Returning Null here
            this.teams[i].setId(i);
            this.teams[i].setRank(i);       
            queue.add(this.teams[i]);
        }       

    }

}

So when I create an object of Tournament. The constructor calls the generateTeams() method.When I run this , it is returning a NullPointerException at the line: this.teams[i] = new Team(); (Which is highlighted in bold).

For some reason it is not instantiating the Team() object and hence assigning a null value to teams[i]

New to OOPS and nested classes. If possible explain in detail.

Thanks in advance.

VPK
  • 2,896
  • 1
  • 23
  • 34
100rabh
  • 133
  • 1
  • 8

1 Answers1

2

You need to instantiate the array first

this.teams = new Team[noOfTeams];

for (int i = 0; i < noOfTeams; i++) 
{     
    this.teams[i] = new Team();   
    this.teams[i].setId(i);
    this.teams[i].setRank(i);       
    queue.add(this.teams[i]);
} 

But as you are adding Team Objects to a queue, why do you even need an Array?

Scary Wombat
  • 41,782
  • 5
  • 32
  • 62
  • Still having the same issue , returns NullPointerException at this.teams[i]setId(i); – 100rabh Jul 26 '18 at 04:15
  • 1
    Did you do `this.teams = new Team[noOfTeams];` ? – Scary Wombat Jul 26 '18 at 04:16
  • Yes I did as mentioned . Issue still persists. As mentioned , removed the array as I am adding in the queue anyway. Works well...! Thanks..! – 100rabh Jul 26 '18 at 04:18
  • 1
    *Yes I did as mentioned* - where did you mention it? Why don't you edit your question with the code that you are using now. Your comment `// Returning Null here` does not make sense - unless you are throwing an exception in `new Team` but how would I know, you are not sharing that code – Scary Wombat Jul 26 '18 at 04:22
  • Finally fixed it . this.teams = new Team[noOfTeams]; and then in the loop did this teams[i] = new Team(); Works as expected now. Thanks for the help..! – 100rabh Jul 26 '18 at 04:23
  • In your answer add in the loop this.teams[i] = new Team(); . That should do. – 100rabh Jul 26 '18 at 04:25