Decrement a value from an existing array if a condition has met using a method - OOP

Viewed 61

I am trying to create a method for a LIBRARY exercise, however, I have some issues with the method RentBook(). Basically, I use to a method to add a book that I want to rent, when using my code it decrements -1 all stocks instead of the one is chosen.

code:

public String rentBook(Book book) {
    for (int i = 0; i < books.length; i++) {
        if ((books[i].equals(book)))
            inStock[i]--;
        }
        return "book name" + book;
    }
}

my equals function:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Book other = (Book) obj;
    if (id != other.id)
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
        return false;
    return true;
}

what I get:

[11, 39, 43, 1, 12, 3]

What I want:

[12, 39, 44, 2, 13, 4]

1 Answers

Try debugging your program.

  • Put some print statements in the equals method to print the two books you are comparing to see if that is how you want to compare? Print them at different locations in the logic and label them accordingly.
  • Use some specially made book objects to test various equals conditions.
  • And print the instock values after each decrement is made.

One of the best debugging tools around is the print statement. Use it liberally.

Related