基本上我有一个主要类,我声明我的对象,然后在我的Person类中,我有一个方法,用于添加和对象在Person类中创建的数组。由于某种原因,这适用于第一个项目,但所有其余的只返回false(如果项目已添加到数组则返回true,如果项目未添加到数组则返回false)。这是我的主要方法:
Department dept = new Department(4);
Person john = new Person("John", 35);
System.out.println(dept.addPerson(john));
以及无效的课程:
private Person[] people;
private int count;
public Department(int count){
people = new Person[count];
}
public boolean addPerson(Person x){
boolean found = false;
for(int i = 0; i < people.length; i++){
if (people[i] == null){
people[i] = x;
found = true;
}
}
return found;
}
答案 0 :(得分:0)
添加内容后,您需要打破for循环。您使用现在添加的第一个人填充阵列。
for(int i = 0; i < people.length; i++){
if (people[i] == null){
people[i] = x;
found = true;
}
}
应该是
for(int i = 0; i < people.length; i++){
if (people[i] == null){
people[i] = x;
found = true;
break;
}
}
答案 1 :(得分:0)
您第一次调用该方法时,您正在填充整个数组。所以下一次调用时索引不会为空
public boolean addPerson(Person x){
boolean found = false;
for(int i = 0; i < people.length; i++){ // you're filling the array in this loop
if (people[i] == null){
people[i] = x;
found = true;
}
}
return found;
}