【问题标题】:Accessing class array field访问类数组字段
【发布时间】:2013-02-01 14:50:17
【问题描述】:

我在访问 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

【问题讨论】:

  • 与问题无关,您应该使用equals 函数比较字符串,而不是==。否则你会发现这种比较几乎永远不会奏效——请参阅stackoverflow.com/questions/513832/… 了解更多信息。

标签: java arrays get field


【解决方案1】:

你交换了两个东西,pers1.children.name.get(i) 应该是pers1.children.get(i).name

由于我们在这里,您正在将字符串与== 进行比较,此比较对象的引用,请改用equals(..)。看看here

【讨论】:

  • 就是这样。非常感谢。
【解决方案2】:

不要使用“==”进行字符串比较;它没有按照你的想法做。你想写成:

if (mother.name.equals(pers1.name)) { ...

当然,这是一种有点危险的方法,因为如果 mothermother.name 为空,您将得到 NullPointerExceptions。所以你会想做一些防御性编程。

if (mother == null) return false;
if (pers1 == null) return false;
if (mother.name != null && mother.name.equals(pers1.name)) ....

【讨论】:

    【解决方案3】:

    看起来您正在使用 == 而不是 equals() 函数来比较字符串。

    尝试像下面这样改变这一行:

    if (pers1.children.name.get(i).equals(name))
    

    【讨论】:

      猜你喜欢
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多