1

我不明白爲什麼我得到一個不兼容數據類型的錯誤,我使用float作爲財務價值,我不想超過兩位小數!Java-使用浮點型 - 構造函數錯誤

我的印象是,你可以用float爲此下,但是我得到退還給我一個錯誤說,

構造雜誌不能應用於給定類型。

當我剛做float 7,而不是7.99,它工作正常!

我誤解了float是什麼,我需要用double來代替嗎?

我只會展示我的雜誌課程和一些我的測試課程來演示。

測試類:

以下是我的測試類試圖用float到小數點後兩位的段:

public static void main() 
{ 
    Magazine magazine1 = new Magazine("SanYonic Publishing", "Ayup Magazine", 7.99, "Yeshumenku Suni", "12/09/2011"); 

    System.out.println(); 
    magazine1.getEditor(); 
    magazine1.getDate(); 
    magazine1.getPublisher(); 
    magazine1.getPublicationTitle(); 
    magazine1.getPrice(); 
    System.out.println(); 
    … 
} 

Magazine類:

/** 
* Magazine Class - This class represents Magazine Objects 
*/ 
public class Magazine extends Publication 
{ 

    private String editor; 
    private String date; 

    public Magazine(String publisherIn , String publicationTitleIn, float priceIn, String editorIn, String dateIn) 
    { 
     super (publisherIn , publicationTitleIn, priceIn); 

     editor = editorIn; 
     date = dateIn; 
    } 

    public void setPublication(String publisherIn, String publicationTitleIn, float priceIn) 
    { 
     publisherIn = publisher; 
     publicationTitleIn = publicationTitle; 
     priceIn = price; 
    } 

    public String getEditor() 
    { 
     System.out.println("The editor of this magazine is " + editor); 
     return (editor); 
    } 

    public String getDate() 
    { 
     System.out.println("The publication date of this magazine is " + date); 
     return (date); 
    } 

    public String getPublisher() 
    { 
     System.out.println("The publisher of this magazine is " + publisher); 
     return (publisher); 
    } 

    public String getPublicationTitle() 
    { 
     System.out.println("The publication title of this magazine is " + publicationTitle); 
     return (publicationTitle); 
    } 

    public float getPrice() 
    { 
     System.out.println("The price of this magazine is £" + price); 
     return (price); 
    } 
} 
+4

我建議你不要使用'float'(或'double')進行財務計算。浮點數不精確,你可以得到奇怪的舍入誤差。使用整數或定點算法通常要好得多,即按照整數美分計算所有內容或使用BigDecimal類。 –

+1

我強烈建議你使用BigDecimal而不是float/double,因爲基元類型有四捨五入的問題存儲十進制值的大型子集。 –

回答

3

您需要

Magazine magazine1 = new Magazine ("SanYonic Publishing", "Ayup Magazine", 7.99f, "Yeshumenku Suni", "12/09/2011");

注意7.99f來解決編譯問題。

請注意,浮動和雙打都不適合貨幣計算(如果您關心準確性),因爲它們只能表示一組離散的值。所有貨幣計算都應該使用BigDecimal完成。

+0

哈哈哈facepalm; 非常感謝你,我覺得我應該得到一個耳光! – Phil

+1

謝謝大家我已經更改爲BisgDecimal – Phil

3

在Java中,默認情況下,其中有一個小數點的數字是double。嘗試7.99f

另外,如果您使用貨幣進行計算,您應該看看BigDecimal以避免後來出現奇怪的舍入誤差。

+0

謝謝傑弗瑞,我試圖實現Bigdecimal,因爲我不是奮鬥,但掙扎, 我已經導入了java.math,java.lang.Object和java.lang。數字, 然後我定義我的價格變量時,卻放置BigDecimal而不是浮動,但不知道如何在我的測試中定義我的號碼。 – Phil