[英]Why isn't my object being added to my array?
我有一個 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
只添加了第一個屬性......關於為什么的任何建議?
因為return i;
. 一旦添加了一個屬性,就退出該方法。
希望有幫助
我有一個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
在另一個類中發現了一個看似無關的方法,該方法導致對象未存儲在數組中。 感謝您的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.