Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA so basically i have an array of BookStock named BookShelf, and i need to ge

ID: 3818180 • Letter: J

Question

JAVA so basically i have an array of BookStock named BookShelf, and i need to get this method to addOrUpdate a book in the bookshelf, or if the book already exists there, I need to Update its quantity. The Method header must be exactly public void addOrUpdateBookStock(Book book, float quantity) as per the assignment.

public void addOrUpdateBookStock(Book book, float quantity){
BookStock x = new BookStock (book.getName(), book.getAuthor(), quantity);

for (int i = 0; i < BookShelf.size(); i++){
   if (BookShelf.get(i).getName().equals(x.getName())){
       BookShelf.get(i).setQuantity(quantity);
   }
   else {
       BookShelf.add(x);
   }
      
}

The problem is: when i try to test it, nothing is getting added into the array!

Explanation / Answer

Answer:

Hi

I have updated your method. it should work for you.

public void addOrUpdateBookStock(Book book, float quantity){
BookStock x = new BookStock (book.getName(), book.getAuthor(), quantity);

boolean found = false;

for (int i = 0; i < BookShelf.size(); i++){
   if (BookShelf.get(i).getName().equals(x.getName())){
       BookShelf.get(i).setQuantity(quantity);

found = true;
   }
}

if(!found) {

BookShelf.add(x);
   

}
}