【问题标题】:How to return an object inside an array?如何返回数组中的对象?
【发布时间】:2021-02-11 21:06:52
【问题描述】:

我有一个大学作业,但我被一个问题困扰了很长一段时间。

所以,我必须首先在方法中返回一个名为 Fruit 的对象(这是我需要帮助的方法)。

(Fruit 在另一个类中定义,像这样:Fruit(String name, Stringnickname, int taste)。)

方法首先是为了返回味道最好的水果。

但我一直有 NullPointerException 用于口味或水果。我确实理解错误的含义,但我不知道如何纠正它。 感谢那些可以提供帮助的人!抱歉英语不好。

public class Four {
    private Fruit[] fruits;
    Four(Fruit f1, Fruit f2, Fruit f3, Fruit f4) {
        Fruit[] m = new Fruit[4];
        m[0] = f1;
        m[1] = f2;
        m[2] = f3;
        m[3] = f4;
    }

    public Fruit[] getFruit() {
        return fruits;
    }

    public Fruit first() { //THIS FIRST LINE CAN'T CHANGE
        Fruit[] e = new Fruit[4];
        Fruit f = e[0];
        for (int i = 1; i < 3; i++) {
            if (f.taste > e[i].taste) {
                f = e[i];
            }
        }
        return f;
    }

    public static void main(String[] args) {
        Fruit f1 = new Fruit("Apple", "Appie", 5);
        Fruit f2 = new Fruit("Strawberry", "Strawy", 20);
        Fruit f3 = new Fruit("Banana", "Banie", 18);
        Fruit f4 = new Fruit("Orange", "Orangi", 8);
        Four m = new Four(f1, f2, f3, f4);
        System.out.println(m.first());
    }
}

【问题讨论】:

    标签: java arrays object


    【解决方案1】:

    在代码中

    Fruit [] e = new Fruit[4];
    Fruit f = e[0];
    

    访问的数组索引e[0] 有一个null 值。所以f.taste &gt; e[i].taste 会抛出 NPE。 (任何e[i]. 都会抛出NPE)

    建议的更改

    构造函数

    Fruit [] m = new Fruit[4];.

    这必须更改为fruits = new Fruit[4];(并且所有对m[] 的分配都应改为fruits[]

    这将有助于同一对象的其他部分访问这些构造值。

    否则,fruits 实例变量将是 null 并且不会跟踪对象的状态。

    第一种方法

    Fruit [] e = new Fruit[4];

    对构造函数进行必要的更改后, 上面一行可以改成Fruit [] e = this.fruits;(或者直接访问fruits[]而不是赋值给e)。

    这将确保在 first 方法中使用预期的对象状态。

    【讨论】:

    • @Evelyne,很高兴知道。一切顺利。
    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多