1

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

我的印象是你可以用 a 来做到这一点float,但是我收到一个错误返回给我说,

构造函数杂志不能应用于给定类型。

当我只制作float7 而不是 7.99 时,它工作正常!

我是否误解了 afloat是什么,我需要使用 adouble代替吗?

我只会展示我的杂志课和一些我的测试课来演示。

测试类:

以下是我的测试类中尝试使用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

2 回答 2

3

你需要

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

注意7.99f修复编译问题。

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

于 2012-01-18T21:35:58.307 回答
3

在 Java 中,默认情况下带有小数点的数字是 a double。试试7.99f

此外,如果您正在使用货币进行计算,您应该查看一下BigDecimal以避免以后出现奇怪的舍入错误。

于 2012-01-18T21:38:27.053 回答