【发布时间】:2019-10-23 23:56:32
【问题描述】:
我正在为我的计算机科学课上的实验室创建一个书店。它使用三个相互交互的类来创建一个书店,可以添加书籍、销售书籍、展示图书馆等等。我正在使用一组对象。当我向图书馆添加多本书时,我的问题就出现了,然后我尝试访问它们以出售它们。我认为问题在于我用来确定我们是否有要出售的特定书籍的“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.
【问题讨论】:
-
不确定你的问题是什么,但你不需要检查
bookstore.sellBook(title, quant);的返回值 -
您发布的代码不是minimal reproducible example,正如有人在您发布的this other question 中评论的那样。您是否阅读了有关如何发布 MRE 的说明?
-
我猜你可能有一个名为 books 的类。您可以使用
Collection来安排它们。在本例中为HashMap<String,Book>,其中String是书名(假设您可以获得唯一的书名)。然后,您可以使用Book currentBook = bookMap.get("<book title>");轻松检索一本书,然后使用currentBook执行任何操作
标签: java loops class for-loop methods