I am creating a bookstore for a lab in my computer science class. It uses three classes that interact with each other to create a bookstore that adds books, sells books, displays the library, and so on. I am using an array of objects. My issue comes when I'm adding multiple books to the library, then I try to access them to sell them. I think the issue lies with the "inStock" method that I use to determine if we have a specific book to sell. I'm not sure how to access all the books that I added to sell them, and I'm not sure if my method is the best way to do this.
Whenever I try to sell a book that isn't the first one that I added, the program claims that they do not have that book in stock, even though I can display all the books with a different method.
How could I get this method to detect all the listed books that I added with the inStock method?
// Search for the book...if found, adjust the quantity.
// otherwise, Book not in the BookStore.
for(int i = 0; i < totalbooks; i++) {
if(title.equals(books[i].getTitle())) {
if(quantity <= books[i].getQuantity()) {
return true;
}
else
return false;
}
else return false;
}
return false;
}
//this is the inStock method^
public boolean sellBook(String title, int quantity) {
// Checks to see if the books are in stock.
for(int i = 0; i < totalbooks; i++) {
if(title.equals(books[i].getTitle())) {
if(quantity <= books[i].getQuantity()) {
gross = gross + books[i].getQuantity()*books[i].getPrice();
books[i].subtractQuantity(quantity);
return true;
}
else
return false;
}
else
return false;
}
return false;
}
//this is the method I use to sell the books
case 2: System.out.println("Please enter the book title.");
title = input.next();
System.out.println();
//input.hasNext();
if(!(bookstore.inStock(title, quant))) {
System.out.println("I'm sorry this book is not in stock.");
}
else {
System.out.println("How many copies would you like to buy?");
quant = input.nextInt();
if(bookstore.inStock(title, quant)) {
bookstore.sellBook(title, quant);
System.out.println("You just bought " + quant +" copies of " + title);
}
else
System.out.println("Error: Not enough copies in stock for your purchase."); break;
//this is a part of the demo class that I use to try to sell the book.
The issue is indeed in your inStock method - return statement immediately stops the execution of a method. There is no chance for other books apart from the first one to be checked for availability. In fact, you only need two return statements:
for (int i = 0; i < totalbooks; i++) {
if(title.equals(books[i].getTitle())) {
return quantity <= books[i].getQuantity();
}
}
return false;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments