如何在没有 NullPointerException 的情况下返回数组对象? [英] How to return an array object without NullPointerException?

查看:79
本文介绍了如何在没有 NullPointerException 的情况下返回数组对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明:

private Man[] man;  

这是初始化:

Man[] man = new Man[1];

    for (int i = 0; i < 1; i++){
        man[i] = new Man();
            for (int j = 0; j < 3; j++){
                man[i].eatThis(table.foods[table.topFood-1]);
                table.topFood--;
            }
    }

想打印这个:

System.out.println(getMan(0));

转到:

public Man getMan(int k){
 return man[k];
}

但我收到 NullPointerException.为什么?同时:

but I receive NullPointerException. Why? While:

System.out.println(man[0]);

工作正常.

Exception in thread "main" java.lang.NullPointerException
at ManRunning.getMan(ManRunning.java:80)
at ManRunning.newGame(ManRunning.java:133)
at ManRunning.<init>(ManRunning.java:57)
at RunDevilRun.main(RunDevilRun.java:9)

推荐答案

行(1)

Man[] man = new Man[1];

隐藏在这行(2)中声明的实例变量

is hiding the instance variable declared in this line (2)

private Man[] man;

任何体面的 IDE 都会对此显示警告.

any decent IDE would show a warning for this.

这里是你应该如何初始化第 (1) 行中用第 (2) 行声明的数组 man

here is how you should initialize the array man in the line (1) declared with line (2)

man = new Man[1];

这篇关于如何在没有 NullPointerException 的情况下返回数组对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆