java中的工资单结果为0

时间:2016-10-05 23:18:52

标签: java eclipse

问题是:

设计一个薪资类,其中包含员工姓名,身份证号码,每小时工资率和工作小时数的字段。编写适当的访问器和mutator方法abd一个构造函数,该构造函数接受员工的姓名和ID号作为agruments。该班级还应该有一种方法,该方法返回员工的总薪酬,计算为工作小时数乘以小时工资率。编写一个程序,通过创建Payroll对象来演示该类,然后要求用户输入员工的数据。该计划应显示所赚取的总薪酬 这是我为班级所拥有的东西

Thread.Sleep

构造函数

import java.util.Scanner;   //Needed for scanner class.
public class Payroll
{
    private String EmployeeName;
    private int IDnumber;
    private double HourlyPayRate;
    private double HoursWorked;
    private double GrossPay;

    /**
        Constructor
        @param Name The name to store in EmployeeName.
        @param ID The ID to store in Employee ID number.
    */
    public Payroll(String Name, int ID)
    {
        EmployeeName = Name;
        IDnumber = ID;
    }
    public String getEmployeeName()
    {
        return EmployeeName;
    }
    public int getIDnumber()
    {
        return IDnumber;
    }
    public void setHourlyPayRate(double HourlyRate)
    {
        HourlyPayRate = HourlyRate;
    }
    public double getHourlyPayRate()
    {
        return HourlyPayRate;
    }
    public void setHoursWorked(double hoursWorked)
    {
        HoursWorked = hoursWorked;
    }
    public double getHoursWorked()
    {
        return HoursWorked;
    }
    public double getGrossPay()
    {
        return HourlyPayRate * HoursWorked;
    }
}

当我编译它时,我没有得到任何错误,但我最后得到了grosspay = 0.0的结果。

1 个答案:

答案 0 :(得分:0)

您创建了一个新的Payroll对象

Payroll pay = new Payroll(EmployeeName, IDnumber);

并在print语句中调用getGrossPay()方法

pay.getGrossPay()

该方法执行以下操作:

return HourlyPayRate * HoursWorked;

因为你从未设置HourlyPayRateHoursWorked,当然该方法将返回0。

要解决此问题,请将这些值设置为您从用户读取的变量:

pay.setHoursWorked(HoursWorked);
pay.setHourlyPayRate(HourlyPayRate);

您可以在创建Payroll对象之后但在调用getGrossPay()方法之前添加这些行。因此,代码的最后四行现在应如下所示:

Payroll pay = new Payroll(EmployeeName, IDnumber);

//set pay rate and hours worked
pay.setHoursWorked(HoursWorked);
pay.setHourlyPayRate(HourlyPayRate);

//Get the Gross Pay of the employee.
System.out.println("The gross pay of " + EmployeeName + " is: " + pay.getGrossPay());