Home > database >  What is the mistake I made that cannot read the length of the array object?
What is the mistake I made that cannot read the length of the array object?

Time:11-23

public int addFighter()
{
    if(team==null)
    {
        Team[] team=new Team[1];//increase the size by 1 from null to 1
        team[0]=new Team(); //calling default constructor
        return team.length;//the array length here is printable
    }   
    
}

I have a setter to save added information:

public void setData(String type, int healthUnits)
{
    int length=this.team.length;//NullPointerException
    this.team[length-1].setType(type);
    this.team[length-1].setHealth(healthUnits);
}

What is my problem here?

In addFighter(), when I check the array object is null, then I declare the array size is 1, and initialize team[0] by calling default constructor. It can read the length of array object is 1 in addFighter(), but why the length cannot be read in setData(), since I already initizlized the array object from null to 1?

From my understing, NPE happens when uninitizlized variable or object being called, but why in my case, NPE happends when my object is initizlized?

I don't know what mistake I made, need some inspirations. Thanks :)

CodePudding user response:

Team[] team=new Team[1];

The way you have written this line creates a new variable, also named team, with no relationship whatsoever to this.team.

The correct way to do what you want is to replace this line with

team=new Team[1];

CodePudding user response:

Use this instead,

public int addFighter()
{
    if(team==null)
    {
        team=new Team[1];//increase the size by 1 from null to 1
        team[0]=new Team(); //calling default constructor
        return team.length;//the array length here is printable
    }   
    
}
  • Related