【发布时间】:2014-07-23 14:39:43
【问题描述】:
我正在为一家书店编写一个库存程序,该程序由两个类和这些类中的多个方法组成。
我遇到最多问题的方法是我的 purchase() 方法,它应该以交互方式处理购买,在购买后更新数组,并显示售出物品的总数和当天的总收入。
该方法应该遵循以下 10 个步骤:
要求用户输入他们想购买的图书的 ISBN 号。
在数组中搜索包含该 ISBN 的对象。
如果在数组中未找到 ISBN,则显示一条消息,说明我们没有该书。
如果找到 ISBN 但份数为 0,则显示该书缺货的消息。
如果找到 ISBN 且份数大于 0,请询问用户他们想购买多少份。
如果他们输入的数字大于数组中该书的副本数,则显示一条消息说明并要求他们输入另一个数量。
当他们为 ISBN 输入 0 时,扫描程序应该关闭
购买完成后,我需要通过减去已购买的特定书籍的副本数来更新数组。
打印更新后的数组。
显示购买了多少本书,以及从购买中赚了多少钱。
但是当我编写代码时,在程序提示我输入 ISBN 之后,什么都没有发生,它只是不断地让我输入数字而没有额外的输出。
这是我为这个方法提供的代码。我很确定这可能是我的循环的问题,因为我不太擅长循环。谁能发现我做错了什么?
public static Book[] purchase(Book[] books) {
int itemsSold = 0;
double totalMade = 0;
double price;
int copies;
String isbn;
Scanner input = new Scanner(System.in);
int desiredCopies = 0;
int index;
double total = 0;
System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
String desiredIsbn = input.next();
for (index = 0; index < books.length; index++) {
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() > 0) {
System.out.println("How many copies of this book would you like to purchase?");
if (!books[index].getISBN().equals(desiredIsbn))
System.out.println("We do not have that book in our inventory.");
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() == 0)
System.out.println("That book is currently out of stock.");
desiredCopies = input.nextInt();
}
if (desiredCopies > books[index].getCopies())
System.out.println("We only have " + books[index].getCopies() + "in stock. Please select another quantity: ");
desiredCopies = input.nextInt();
books[index].setCopies(books[index].getCopies() - desiredCopies);
if (input.next().equals(0))
System.out.println("Thank you for your purchase, your order total is: $" + total);
input.close();
total = books[index].getPrice() * desiredCopies;
itemsSold += desiredCopies;
totalMade += total;
System.out.print(books[index]);
System.out.println("We sold " + itemsSold + " today.");
System.out.println("We made $" + totalMade + "today.");
}
return books;
}
任何帮助将不胜感激。
【问题讨论】:
-
请向我们展示您尝试调试问题的结果。
-
另外一个不请自来的建议——您在尝试调试问题之前来这里的启发式做法从长远来看会伤害您,因为它会阻止您学习关键技术以及调试程序所涉及的思考。我建议您以不同的方式处理未来的问题,使用调试器在 来这里之前分析问题,然后如果您仍然没有解决方案,请发布您的调试尝试结果。否则,您将只学会在这里提出问题,而不是如何解决自己的问题。好的,我完成了。