我不明白为什么会收到数据类型不兼容的错误,我使用float表示财务值,我不想超过两位小数!

我的印象是您可以使用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);
    }
}

最佳答案

你需要

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

请注意7.99f以解决编译问题。

请注意,浮点数和双精度数都不适用于货币计算(如果您关心准确性),因为它们只能表示一组离散值。所有货币计算都应使用BigDecimal进行。

10-08 01:20