Home > Mobile >  Why is my code not adding one to the current Price of the book?
Why is my code not adding one to the current Price of the book?

Time:04-24

public void addDollarToRatingOfFour() {
        double one = 1.0;
        double newBookPrice = 0.0;
        for (Book currBook : this.listOfBooks) {
            if (currBook.getRating() > 4) {
                newBookPrice = one   currBook.getPrice();
            }
            newBookPrice = newBookPrice   1;
        }
    }

With this code it is supposed to add a dollar to all the books with a rating of 4 or above, but in my testing it's not adding a dollar at all to any price. Any Ideas?

CodePudding user response:

You should currBook.setPrice(newcalculatedprice) after recalculating

CodePudding user response:

This looks as though you have this code:
1   double one = 1.0;
2   double newBookPrice = 0.0;
3   for (Book currBook : this.listOfBooks) {
4    if (currBook.getRating() > 4) {
5     newBookPrice = one currBook.getPrice();
6   }
7   newBookPrice = newBookPrice 1;
8   }

So let me ask you a question, what is your book?
currBook right?
So if you want to set its value, you need to modify the property or field value
of that object. You are only setting newBookPrice on line 5 above. Which we know is a different variable, not related to the book object -> currBook

You want something like this on line 5:
currBook.Price = currBook.GetPrice() one;

Additionally, if you are using get/set methods to not access the properties
directly, then you want to do something like this:
currBook.SetPrice(currBook.GetPrice() one);

Finally, it may have happened during testing, but you added 1 again on line 7 and it is outside the loop.

CodePudding user response:

Your code is updating a local variable called newBookPrice. It is not updating the price of the actual books. The local variable then gets thrown away when your method returns.

We can't see your Book class, but I expect that it has a setPrice(...) method. You should be calling that to update the prices of each Book object that needs updating.

  • Related