2015-04-15 57 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

非常感謝您的幫助! –