【问题标题】:Why is o.pet null even though I set it to be a value?为什么 o.pet null 即使我将它设置为一个值?
【发布时间】:2020-12-01 03:47:09
【问题描述】:

我正在 RescueCenter 上做一个 apcs 项目,人们可以在那里收养动物等等。我遇到的问题是,在我的 UI 中,当我尝试列出所选所有者的宠物时,会出现一个异常,说它无法读取 o.pet,因为它为空。我想知道为什么即使我在 Owner 采用函数中将 a 的所有者设置为 this 并在 RescueCenter 采用函数中调用它,它还是 null?

Owner class

void adopt(Animal a) {
            pet = a;
            a.owner = this;
    }

RescueCenter class:

public boolean adopt(String customerName, String animalName) {
        Owner o = new Owner(customerName, age);
        Animal d = new Dog(animalType, animalName, animalBreed, animalAge);
        if (!o.isQualified() || !d.isQualified()) {
            o.qualify();
            d.qualify();
        }
        if (o.isQualified() && d.isQualified()) {
            o.adopt(d);
            d = o.pet;
            adoptableAnimalList.remove(d);
            return true;
        }
            return false;
    }

public String getPet(String currCustomerName) {
        Owner o = new Owner(currCustomerName, age);
        return o.pet.name;
    }

【问题讨论】:

  • 您检查过o.adopt(d); 确实发生了吗?会不会是isQualified的bug,导致合格的宠物或主人不被识别?或者在qualify 中,未能使他们合格?另外,RescueCenter#adopt 实际上在哪里被调用?

标签: java exception null project computer-science


【解决方案1】:

您创建了一个new Owner,但从不调用adopt。 (就此而言,您还可以创建然后丢弃 adopt 中的对象。)您可能寻找的是类似于 Map<String, Owner> 的东西,您可以在其中存储和检索 Owner 对象。

【讨论】:

    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    相关资源
    最近更新 更多