Search code examples
javabigdecimal

BigDecimal in Java error


There are errors all on everything having to do with the price/

import java.math.BigDecimal;

public class Product {

    // Fields
    String name;
    String description;
    BigDecimal price = new BigDecimal(3.0);
    int quantity;
    String barcode;
    String image;
    static int count;


    // Constructors
    public Product()
    {
        name = "";
        description = "";
        price = 0;       
        quantity = 0;
        barcode = "";
        image = "";
    }

    public Product(String n, String d, double p, int q, String b, String i)
    {
        name = n;
        description = d;
        price = p;
        quantity = q;
        barcode = b;
        image = i;
    }



    // Get/Set methods

    // description getter and setter
    public String getDescription()
    {
        return description;
    }

    public void setDescription(String d)
    {
        this.description = d;
    }


    // name getter and setter
    public String getName()
    {
        return name;
    }

    public void setName(String d)
    {
        this.name = d;
    }


    // price getter and setter
    public double getPrice()
    {
        return price;
    }

    public void setPrice(double d)
    {
        this.price = d;
    }


    // quantity getter and setter
    public int getQuantity()
    {
        return quantity;
    }

    public void setQuantity(int d)
    {
        this.quantity = d;
    }


    // barcode getter and setter
    public String getBarcode()
    {
        return barcode;
    }

    public void setBarcode(String d)
    {
        this.barcode = d;
    }


    // image getter and setter
    public String getImage()
    {
        return image;
    }

    public void setImage(String d)
    {
        this.image = d;
    }

}

My questions is why is there an error for all of my price parts. I need it to be a big decimal, but how to I fix the errors?


Solution

  • Well your constructor is giving the value of p, which is your bigDecimal, be a double. You need to supply it a BigDecimal instead :) So in the arguemnts, supply that instead of "double" for "p".

    Java uses this thing called "static checking" which means even as you're typing, it can tell that, if for example, you have a variable declared as a BigDecimal, and you try to set it equal to a variable of another type, then there's an error. If you hover over the little red squiggly line under the variables it gives you pretty useful info!