第一次在这里海报。我已经走到了尽头,准备放弃我对编程职业的追求。我没有交上我的最后一个作业,因为我无法让我的程序运行。现在,我正在自己做一些额外的练习。一个使用数组的简单练习作业,我无法弄清楚它的最后一点。有人可以告诉我我在这里做错了什么吗?当我运行它时,我可以输入数据,但程序在显示输出之前退出并出现以下错误:
Exception in thread "main" java.lang.NullPointerException
at Payroll.getGrossPay(Payroll.java:47)
at PayrollCalc.main(PayrollCalc.java:32)
我可以分别显示小时数和 payRate,但我不能显示 GrossPay。我对我的构造函数也不满意,但不太确定如何处理它。这个问题需要我初始化 Payroll 类中的数组。
public class Payroll {
private final int NUM_EMPLOYEES = 3;
private int[] employeeId = {5658845, 4520125, 7895122}, empId, hours;
private double[] payRate, wages, grossPay;
public Payroll()
{
empId = employeeId;
}
public void setEmployeeId(int[] employeeId)
{
empId = employeeId;
}
public void setEmpHours(int[] empHoursIn)
{
hours = empHoursIn;
}
public void setEmpPayRate(double[] empPayRateIn)
{
payRate = empPayRateIn;
}
public int[] getEmployeeId()
{
return empId;
}
public int[] getEmpHours()
{
return hours;
}
public double[] getEmpPayRate()
{
return payRate;
}
public double[] getGrossPay()
{
for (int count = 0; count < NUM_EMPLOYEES; count++)
{
grossPay[count] = getEmpPayRate()[count] * getEmpHours()[count];
}
return grossPay;
}
}
导入 java.util.Scanner;
public class PayrollCalc
{
public static void main(String[] args)
{
int count;
final int NUM_EMPLOYEES = 3;
int[] empHours = new int[NUM_EMPLOYEES];
double[] empPayRate = new double[NUM_EMPLOYEES];
Scanner keyboard = new Scanner(System.in);
Payroll payroll = new Payroll();
for (count = 0; count < NUM_EMPLOYEES; count++)
{
System.out.print("Enter total hours for employee " +
payroll.getEmployeeId()[count] + ": ");
empHours[count] = keyboard.nextInt();
payroll.setEmpHours(empHours);
System.out.print("Enter pay rate for employee " +
payroll.getEmployeeId()[count] + ": ");
empPayRate[count] = keyboard.nextDouble();
payroll.setEmpPayRate(empPayRate);
}
System.out.println("\nEMPLOYEE ID\tGROSS PAY");
System.out.println("----------- ---------");
for (count = 0; count < NUM_EMPLOYEES; count++)
{
System.out.println(payroll.getEmployeeId()[count] + "\t\t" +
payroll.getGrossPay()[count]);
}
}
}
在此先感谢您的帮助!
史蒂夫