Search code examples
javaif-statementmathbluej

Parameter change with percentage


I have this assignment to make a class that creates product in a store.

One of the requirements is a method that changes the price according to a discount or increase percentage.

This is the method:

public void changePrice(double percent) {

    if ( percent > 0) {
        _price+= ((_price * percent) /100);
    }
    else if (percent < 0) {
        _price-= ((_price * percent) /100);

    }
    else {
    }
}

for some reason it does not recognize negative numbers, and treats them like positive. I tried a couple of variations of this with same results.


Solution

  • The if, else if is negating the minus in percent

    public void changePrice(double percent) {
        _price+= ((_price * percent) /100);
    }
    

    If percent is +10% the price would increase by 10% similarly if percent is -10% the price will reduce by 10%