首页 > 解决方案 > 调用内部带有 for 循环的方法,而不是更新变量

问题描述

我正在为我的计算机科学课上的实验室创建一个书店。它使用三个相互交互的类来创建一个书店,可以添加书籍、销售书籍、展示图书馆等等。我正在使用一组对象。当我向图书馆添加多本书时,我的问题就出现了,然后我尝试访问它们以出售它们。我认为问题在于我用来确定我们是否有要出售的特定书籍的“inStock”方法。我不确定如何访问我添加的所有书籍以出售它们,我不确定我的方法是否是最好的方法。

每当我尝试出售不是我添加的第一本书时,该程序声称他们没有该书的库存,即使我可以用不同的方法显示所有书籍。

我怎样才能让这种方法检测我使用 inStock 方法添加的所有列出的书籍?

        // 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.

标签: javaloopsclassfor-loopmethods

解决方案


问题确实出在您的 inStock 方法中 - return语句立即停止方法的执行。除了第一本书之外,没有机会检查其他书籍的可用性。其实只需要两条return语句:

for (int i = 0; i < totalbooks; i++) {
    if(title.equals(books[i].getTitle())) {
        return quantity <= books[i].getQuantity();
    }
}
return false;

推荐阅读