NullPointerException when working with arrays

2019-02-19 13:58发布

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.

Here's the code:

    //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 );

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?

Thanks! -Sean

3条回答
姐就是有狂的资本
2楼-- · 2019-02-19 14:22

You're not creating any Employee objects. Creating the array doesn't create any Employee objects - the array doesn't contain objects, it contains references, and initially all those references are null. You just need:

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

It's worth being very clear about the differences between objects and references - it affects all aspects of the language, from default values, to the assignment operator, to parameter passing, to garbage collection. It can be particularly confusing if you've come from a C++ background, I believe.

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-19 14:30
 employee[ j ] = new Employee();
employee[ j ].setFirstName( nameF );
查看更多
Luminary・发光体
4楼-- · 2019-02-19 14:31

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);
查看更多
登录 后发表回答