我犯的错误是什么不能读取数组对象的长度?
What is the mistake I made that cannot read the length of the array object?
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
}
}
我有一个 setter 来保存添加的信息:
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);
}
我的问题是什么?
在addFighter()中,当我检查数组对象为空时,我声明数组大小为1,并通过调用默认构造函数初始化team[0]。在addFighter()中可以读到数组对象的长度为1,为什么在setData()中读不到长度,因为我已经将数组对象从null初始化为1了?
据我了解,NPE 发生在未初始化的变量或对象被调用时,但为什么在我的情况下,NPE 发生在我的对象被初始化时?
我不知道我犯了什么错误,需要一些灵感。谢谢:)
Team[] team=new Team[1];
你写这行的方式创建了一个新变量,也命名为 team
,与 this.team
.
没有任何关系
做你想做的正确方法是用
替换这一行
team=new Team[1];
改用这个,
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
}
}
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
}
}
我有一个 setter 来保存添加的信息:
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);
}
我的问题是什么?
在addFighter()中,当我检查数组对象为空时,我声明数组大小为1,并通过调用默认构造函数初始化team[0]。在addFighter()中可以读到数组对象的长度为1,为什么在setData()中读不到长度,因为我已经将数组对象从null初始化为1了?
据我了解,NPE 发生在未初始化的变量或对象被调用时,但为什么在我的情况下,NPE 发生在我的对象被初始化时?
我不知道我犯了什么错误,需要一些灵感。谢谢:)
Team[] team=new Team[1];
你写这行的方式创建了一个新变量,也命名为 team
,与 this.team
.
做你想做的正确方法是用
替换这一行team=new Team[1];
改用这个,
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
}
}