我试图从txt文件返回有关基于工资的员工的某些变量,代码将编译但不打印出来。 这就是我目前在项目中所做的事情:
public class PayrollPreparation {
private File source;
private Scanner input;
private String payrollType;
private int employeeID;
private String employeeName;
private int hoursWorked;
private double payRate;
private double straightPay;
public void printEmployeeData() {
System.out.println("Employee ID Name Hours Worked Pay Amount");
try {
source = new File("Payroll.txt");
input = new Scanner(source);
input.useDelimiter("[,\n]");
} catch (Exception e) {
System.out.println(e);
}
while (input.hasNext()) {
if (payrollType.equals("S")) {
employeeID = input.nextInt();
employeeName = input.next();
hoursWorked = input.nextInt();
payRate = input.nextDouble();
payrollType = input.next();
straightPay = (hoursWorked * payRate);
System.out.println(" " + employeeID + " " + employeeName
+ " "
+ hoursWorked + " " + straightPay);
input.nextLine();
}
}
System.out.println("No More Salaried Employees.");
}
}
代码全部编译但在测试时if
语句出错,并显示java.lang.NullPointerException: null
答案 0 :(得分:0)
您的属性payrollType永远不会初始化。
在null对象上调用equals方法时,此结果为NullPointerException。
最佳做法是始终将常量(在您的情况下为字母S)与对象进行比较。
所以你的代码应该是" S" .equals(payrollType)。