【问题标题】:What is the mistake I made that cannot read the length of the array object?我犯了什么错误,无法读取数组对象的长度?
【发布时间】:2022-01-01 15:06:30
【问题描述】:
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
    }   
    
}

我有一个设置器来保存添加的信息:

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?

我不知道我犯了什么错误,需要一些灵感。谢谢:)

【问题讨论】:

  • 当您在 if 块中有 Team[] team=new Team[1]; 时,您不会将 this.team 的值设置为您正在实例化的数组。您正在该 if 块的范围内创建一个新的数组变量。你应该有this.team = new Team[1]
  • 你是不是要把Team[] team=new Team[1];写成this.team=new Team[1];

标签: java arrays nullpointerexception


【解决方案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
    }   
    
}

【讨论】:

    【解决方案2】:
    Team[] team=new Team[1];
    

    您编写此行的方式创建了一个新变量,也称为team,与this.team 没有任何关系。

    做你想做的事情的正确方法是用

    替换这一行
    team=new Team[1];
    

    【讨论】:

    • 非常感谢您帮我找出问题所在!谢谢!
    猜你喜欢
    • 2017-10-12
    • 2016-12-09
    • 1970-01-01
    • 2023-03-03
    • 2021-08-10
    • 2023-01-13
    • 2019-05-13
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多