Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change a value in a set method depending on a boolean's answer in Java?

I’m trying to change the VAT rate of an item depending if it’s a luxury item or not.

I’ve tried using an if inside of my set method but it only uses the pre-set value that I gave it.

private double vat = 0.08;

is my preset value. My get and set methods are:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public double getVat() {
    return this.vat;
}

public void setVat(double vat) {
    if(lux=true) {
    this.vat = 0.10;
    }
    
    else if(lux=false) {
    this.vat = vat;
    }
}

and the variable lux is

private boolean lux;

Also, this is what my constructor looks like:

public ProductTest(String pname, double price, boolean lux) {
    this.pname = pname;
    
    if(price>0) {
    this.price = price;
    }
    else {
    this.price = 0;
    }
    
    this.lux = lux; //If product type is luxury , =true ----- if product type is not luxury, =false
    
}

When I create and object and mark the lux variable as true or false, VAT takes the value of 0.08.

ProductTest p = new ProductTest("apple", 10, true);
System.out.println(p.getVat());

Output: 0.08

ProductTest p = new ProductTest("apple", 10, false);
System.out.println(p.getVat());

Output: 0.08

What can I do to overcome this? Thanks.

>Solution :

You nede to call setVat in the constructor to apply the logic

public ProductTest(String pname, double price, boolean lux) {
    this.pname = pname;
    this.price = Math.max(0, price);
    this.lux = lux;
    setVat(vat);
}

public void setVat(double vat) {
    if (lux) {
        this.vat = 0.10;
    } else {
        this.vat = vat;
    }
}

Could even be shorter with ternary operator

public void setVat(double vat) {
    this.vat = lux ? 0.10 : vat;
}

Or do it differently by putting the logic in the getVat

public ProductTest(String pname, double price, boolean lux) {
    this.pname = pname;
    this.price = Math.max(0, price);
    this.lux = lux;
}

public double getVat() {
    return lux ? 0.10 : vat;
}

public void setVat(double vat) {
    this.vat = vat;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading