2015-04-15 55 views
1

我在我的介绍课程中有一个关于实现的问题。我想出了一个答案,但汇编说,“编译错误(第3行,第9列):可能的精度损失”我很困惑这种精度的损失是什么。
我的家庭作业的问题如下: 回想一下,Person类实现了Comparable接口:Java的实现帮助介绍

public class Person implements Comparable 

现在假设我们想通过他们的工资比较的员工。由于Employee扩展了Person,Employee已经通过Person compareTo方法实现了Comparable,Person compareTo方法按年龄比较Person对象。现在我们想要重写Employee类中的compareTo方法,以便进行薪水比较。

对于此分配,通过为该类实施新的compareTo方法来修改Employee类。在下面提供的空白处输入适当的代码,这样如果员工A的工资低于员工B的工资,则认为员工A被认为少于员工B.此外,如果员工A的工资等于员工B的工资,那么他们应该是平等的。请记住,您输入的代码位于Employee类中。

/** 
    * Compares this object with the specified object for order. 
    * @param o the Object to be compared. 
    */ 
    public int compareTo(Object obj) 
    { 

这里是我的代码

double b= ((Employee)obj).getSalary(); 
    double a= this.salary; 
    return(a-b); 
    } 

这里是Employee类代码:

class Employee extends Person 
{ 

    private double salary; 

    /** 
    * constructor with five args. 
    * @param n the name 
    * @param ag the age 
    * @param ht the height 
    * @param p the phone number 
    * @param the salary 
    */ 
    public Employee(String n, int ag, int ht, String p, double s) 
    { 
    super(n, ag, ht, p); 
    salary = s; 
    } 

    /** 
    * Get the salary. 
    * @return double the salary. 
    */ 
    public double getSalary() 
    { 
    return salary; 
    } 

    /** 
    * Raise the employee's salary by a given percent. 
    * @param percentRaise 
    */ 
    public void raise(double percentRaise) 
    { 
    salary *= (1 + percentRaise); 
    } 

    /** 
    * Compares this object with the specified object for order. 
    * @param o the Object to be compared. 
    */ 
    public int compareTo(Object obj) 
    { 
    /* your code goes here */ 
    } 

    /** 
    * get a String representation of the employee's data. 
    * @return String the representation of the data. 
    */ 
    public String toString() 
    { 
    return super.toString() + " $" + getSalary(); 
    } 

} 

任何帮助,让我正确回答将是非常赞赏。我一直在研究这个单独的问题超过一个小时,而编译错误令我困惑不已。谢谢!

回答

2

我相信精度的损失是因为你在一对双精度上执行算术运算并返回结果,但是你的方法头被声明为返回一个int。

尝试铸造你的减法:

public int compareTo(Object obj) 
{ 
    double b= ((Employee)obj).getSalary(); 
    double a= this.salary; 
    return (int) (a-b); 
} 

但是,因为它看起来像你的意图是使工资之间的比较,尝试这样的事情:

public int compareTo(Object obj) 
{ 
    double b= ((Employee)obj).getSalary(); 
    double a= this.salary; 
    return Double.compare(a, b); 
} 
+0

非常感谢你,我傻。我知道有些东西与回归和类型有关,但我无法弄清楚。这是一个巨大的帮助。谢谢 –

4

的问题是, compareTo方法必须返回int,但减去工资产生double。 Java不会让你在没有强制转换的情况下将double隐式转换为int。虽然演员将获得编译代码,但结果可能是错误的。例如,0.4的差异将被转换为int,如0,错误地报告相等。

您可以测试小于,等于或大于的工资,并分别返回-1,0或1。您也可以返回调用Double.compare的结果,通过2个工资。

如果您是初学者,那么您可能并不知道通常Comparable interface是通用的,并且通过提供类型参数来实现。在这种情况下,这回答了“与什么相似?”的问题。 compareTo方法的参数是通用的,因此它采用相同的类型。这也避免了在方法体中需要投入objPerson

public class Person implements Comparable<Person> 

public int compareTo(Person obj) 
+0

非常感谢您的帮助! –