我在for循环中从数组访问字段时遇到问题。我确定我只是弄乱了语法:
public class Person {
String name;
Person mother;
Person father;
ArrayList<Person> children;
public boolean isMotherOf(Person pers1) {
//First check if Persons mother equals pers1
if (mother.name == pers1.name) {
//Second checks if pers1s children contains Person
for (int i = 0; i < pers1.children.size(); i++) {
if (pers1.children.name.get(i) == name) {
// ERROR ON THE LINE ABOVE: "name cannot be resolved or it not a field"
return true;
}
} // END second check
} else { return false; }
} // END method isMotherOf
}
编辑:我的代码包含逻辑错误(比较错误的人)。这个安全检查是否有效,或者当检查pers1的母亲是否有名字时,如果pers1不存在会产生错误吗?
public class Person {
String name;
Person mother;
Person father;
ArrayList<Person> children;
// Checks if THIS person is the mother of pers1
public boolean isMotherOf(Person pers1) {
// Safety check: Both persons exists and Person has children and pers1 has mother
if (name == null || children == null || pers1 == null
|| pers1.mother.name == null) {
return false;
} // END safety check
// First check if Persons name equals pers1's mother
else if (name.equals(pers1.mother.name)) {
// Second check if Persons children contains pers1
for (int i = 0; i < children.size(); i++) {
if (children.get(i).name.equals(pers1.name)) {
return true;
}
} // END second check
} // END first check
return false;
} // END method isMotherOf
} // END class Person
答案 0 :(得分:4)
您交换了两件事,pers1.children.name.get(i)
应为pers1.children.get(i).name
。
由于我们在这里,您正在将字符串与==
进行比较,这比较了对象的引用,而是使用equals(..)
。请查看here。
答案 1 :(得分:0)
您似乎正在使用==
代替equals()
函数来比较字符串。
尝试按以下方式更改此行:
if (pers1.children.name.get(i).equals(name))
答案 2 :(得分:0)
不要使用“==”进行字符串比较;这不符合你的想法。你想把它写成:
if (mother.name.equals(pers1.name)) { ...
当然,这是一种稍微危险的方法,因为如果NullPointerException
或mother
为空,您将获得mother.name
。所以你会想做一些防御性的编程。
if (mother == null) return false;
if (pers1 == null) return false;
if (mother.name != null && mother.name.equals(pers1.name)) ....