运行此代码时,我不断收到此错误,但我不知道如何解决。我已经使用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;
}
}
最佳答案
将一个构造函数添加到您的Payroll类中,以初始化两个数组hours
和payRate
,如下所示:
public Payroll(){
hours = new int[employeeID.length];
payRate = new double[employeeID.length];
}
然后,当您像当前一样在主类中创建Payroll对象时,使用以下行:
Payroll newEmployee = new Payroll();
数组将被初始化。关于java - Java:线程“main”中的异常java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19989435/