gpt4 book ai didi

java - 为什么我的对象没有添加到我的数组中?

转载 作者:行者123 更新时间:2023-12-01 17:41:59 24 4
gpt4 key购买 nike

我有一个 ManagementCompany 数据管理器类,它将有关各种属性的信息存储在名为 properties[] 的 Property(我定义的类)类型数组中。该类的方法之一旨在向该数组添加属性,称为 addProperty(Property p)。它应该获取给定的属性并将其添加到第一个可用空间中的数组中(如果有的话)(如下所示:)

Property[] properties = new Property[5];

public int addProperty(Property p) {
if (isArrayFull()) //Method returns true if there is no space, false otherwise
return -1;
else if (p == null) //Make sure p is valid
return -2;
for (int i = 0 ; i < properties.length; i++) { //Loop through all elements in the array
if (properties[i] == null) { //If the space is empty
properties[i] = new Property(p); //Assign a new property to it
return i; //Return the index of the new property
}
}
return -10; //Should never happen, but need it to compile
}

但是,当我创建属性并向数组添加属性时,仅添加第一个属性。添加第一个属性后,程序不会继续添加到第一个可用空间,相反,它似乎只是忽略它们。它不会替换第一个,也不会将其添加到数组(数组的长度初始化为 5)。关于原因有什么建议吗?

我正在运行的测试:

ManagementCompany mgmCmp = new ManagementCompany();


Property p1 = new Property("Property 1");
mgmCmp.addProperty(p1);


Property p2 = new Property("Property 2");
mgmCmp.addProperty(p2);

System.out.println(mgmCmp.toString());

结果是:属性 1 null null null null

最佳答案

only the first property is added... Any suggestions as to why?

因为return i;。添加一个属性后,您将退出该方法。

希望有帮助

关于java - 为什么我的对象没有添加到我的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60937824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com