使用数组时的NullPointerException [英] NullPointerException when working with arrays

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

问题描述

我想创建一个在线的Java课程的程序。这个计划包括一个Employee类和一个名称类。我要创建多个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.

这里的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 );

问题是,编译器,运行程序时说,最后一行是一个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?

谢谢!
-Sean

Thanks! -Sean

推荐答案

您创建了一个尺寸 numEmp 的新数组,但默认值是。这意味着数组最初包含 numEmp 空引用。您需要使用来实例化每个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天全站免登陆