处理数组时出现 NullPointerException [英] NullPointerException when working with arrays

查看:23
本文介绍了处理数组时出现 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为在线 Java 课程创建程序.该程序包括一个 Employee 类和一个 Name 类.我必须创建多个 Employee 对象并提示用户输入员工的姓名.我将所有 Employee 对象存储在一个员工数组中.

I am trying to create a program for an online Java course. This program includes an Employee class and a Name class. I have to create multiple Employee objects and prompt the user to enter the employee's name. I am storing all the Employee objects in an employee array.

代码如下:

    //Creates employee array with the number of array elements being however many          
    //employees there are:
    Employee employee[] = new Employee [ numEmp ];

    for( int j = 0; j < numEmp; j++ )
    {
        System.out.println( "Please enter the first name of employee number "
                + ( j + 1 ) );
        Scanner input2 = new Scanner( System.in );
        String nameF = input2.nextLine();

        //This should set the employee object at employee array element "j" to the          
        //String nameF
        employee[ j ].setFirstName( nameF );

问题是编译器在运行程序时说最后一行是 NullPointerException.我不确定我做错了什么.有什么建议吗?

The problem is that the compiler, while running the program, says that the last line is a NullPointerException. I'm not sure what I am doing wrong. Any suggestions?

谢谢!-肖恩

推荐答案

您创建了一个大小为 numEmp 的新数组,但每个元素的默认值为 null>.这意味着该数组最初包含 numEmp 空引用.您需要使用 new 来实例化每个 Employee 对象,然后才能调用它们的方法.

You created a new array with a size of numEmp, but the default value for each element is null. This means that the array initially contains numEmp null references. You need to use new to instantiate each Employee object before you can call methods on them.

您可以在创建数组后立即执行此操作:

You can either do this immediately after you create the array:

Employee employee[] = new Employee [ numEmp ];
for( int j = 0; j < numEmp; j++ )
{
    employee[j] = new Employee();
}

或者您可以在现有循环中执行此操作,就在您第一次需要使用该对象之前:

Or you could do it inside your existing loop, just before you first need to use the object:

employee[j] = new Employee();
employee[j].setFirstName(nameF);

这篇关于处理数组时出现 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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