返回值显示为0.0。为什么会这样?

时间:2015-01-08 16:53:36

标签: java

public   class    employee {

 String empname; 
    int  empcode    ; 
   double basicpay;

    employee()
    {
        empname     =  "";
        empcode     =  0;
        basicpay     =  0.0;
    }
    employee(String n , int p , double q)
    {
        n = empname;
        p = empcode;
        q = basicpay;
    }
    double salarycal()
    {
        double salary,hra,da,allowance,totalsalary;allowance = 0;totalsalary = 0;
        hra = 0.3*basicpay;
        da = 0.4*basicpay;
        salary = basicpay + hra + da;
        if(empcode<=15 && salary<=15000)
        {
            allowance = 0.2*salary;
            if (allowance> 2500)

            allowance  =  allowance - (allowance-2500);
        }
        else 
        {
            allowance = 1000;
         }
        totalsalary =salary + allowance;

        return totalsalary;//the problem is that the total salary is not returned.
    }
}

请说明必须对该计划进行哪些更正。

3 个答案:

答案 0 :(得分:4)

我相信你的一个构造者正在向后做作业。它应该看起来像:

employee(String n , int p , double q)
{
    empname = n;
    empcode = p;
    basicpay = q;
}

答案 1 :(得分:1)

默认构造函数 在默认构造函数中,您正在初始化为零,basicpay = 0.0并且您将所有内容相乘,因此答案为零。

参数化构造函数在参数化构造函数中,您错误地赋值

 employee(String n , int p , double q)
    {
        n = empname;
        p = empcode;
        q = basicpay;
    }

basicpaydouble,即默认值为0.0,因此它也会为您提供零结果。

修改后的代码:

employee(String n , int p , double q) {
    this.empname = n;
    this.empcode = p;
    this.basicpay = q;
}

答案 2 :(得分:0)

它正常工作,因为您将所有内容与0相乘。

hra = 0.3*basicpay; // basicpay is 0. so 0.
da = 0.4*basicpay; // basicpay is 0. so 0.
salary = basicpay + hra + da; // 0+0+0 = 0

basicpay指定非零值。在构造函数中,您已经交换了参数和字段。如果您使用this,则该错误很明显,例如

employee(String n , int p , double q)
  // n = empname;
  // p = empcode;
  // q = basicpay;
  this.empname = n;
  this.empcode = p;
  this.basicpay = q;
}

此外,班级名称(按惯例)应以大写字母开头; Employee