0

运行此代码时,我不断收到此错误,但我不知道如何修复它。我已经做 Java 大约 3 个月了,可以使用一些帮助。基本上,该程序要求用户输入每个员工的工资率和小时数。工资率、小时数和员工人数都是将彼此共享相同索引的数组。当用户输入员工的工资率和小时数时,程序会返回该员工的总工资。除了这个错误不断弹出。请帮忙!

Exception in thread "main" java.lang.NullPointerException
    at chapter.pkg7.lab.Payroll.setPayRate(Payroll.java:41)
    at chapter.pkg7.lab.Chapter7Lab.main(Chapter7Lab.java:45)
Java Result: 1

这是代码:

package chapter.pkg7.lab;

import java.util.Scanner;

public class Chapter7Lab {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
 Payroll newEmployee = new Payroll();
       int[] employeeNum = newEmployee.getEmployeeID();
       double pay;
       int hour;

       for (int i = 0; i < employeeNum.length; i++)
       {
           System.out.println("Please enter the Pay Rate for Employee #" + employeeNum[i]);
           pay = keyboard.nextDouble();
           newEmployee.setPayRate(pay, i);

           System.out.println("Please enter the hours for Employee #" + employeeNum[i]);
           hour = keyboard.nextInt();
           newEmployee.setHours(hour, i);

           System.out.println("Gross pay is: " + newEmployee.getWages(i));
       }



package chapter.pkg7.lab;

public class Payroll {
    private int[] employeeID = new int[] {5658845, 4520125, 7895122, 
        8777541, 8451277, 1302850, 7580489};

    private int[] hours;
    private double[] payRate;
    private double wages;


   public double getWages(int index) {
      wages = hours[index] * payRate[index];
      return wages;
    }


   //Accessors and Mutators
    public int[] getEmployeeID() {
        return employeeID;
    }

    public void setEmployeeID(int[] employeeID) {
        this.employeeID = employeeID;
    }

    public int[] getHours() {
        return hours;
    }

    public void setHours(int hours, int index) {
        this.hours[index] = hours;
    }

    public double[] getPayRate() {
        return payRate;
    }

    public void setPayRate(double payRate, int index) {
        this.payRate[index] = payRate;
    }



}
4

3 回答 3

2

您已将payRate(and hoursand wages) 声明为数组,但它是一个未初始化的实例变量,所以它是null.

初始化它:

private double[] payRate = new double[employeeID.length];

(同样适用于hoursand wages)。

于 2013-11-14T22:11:03.393 回答
0
NullPointerException 

当您不初始化变量或对象并尝试访问该变量或对象时出现

于 2013-11-14T22:23:24.873 回答
0

向您的 Payroll 类添加一个构造函数,用于初始化两个数组hourspayRate 如下所示:

public Payroll(){
   hours = new int[employeeID.length];
   payRate = new double[employeeID.length];
}

然后,当您在主类中创建 Payroll 对象时,就像您当前对行所做的那样:Payroll newEmployee = new Payroll();数组将被初始化。

于 2013-11-14T22:24:01.640 回答