【发布时间】:2020-12-02 14:54:20
【问题描述】:
所以我有一些库存/商店互动,但我找不到解决方案。
玩家应该能够在我的 Item 类构造函数中以预定义的买入/卖出值买卖物品。在扫描仪的帮助下,我可以在没有任何错误的情况下进行销售。但是,如果我购买任何数量,那么整个数量都会以某种方式购买。购买任意数量后,商品数量设置为0。
private void buyItem() {
System.out.println("Which item would you like to buy?");
showStock();
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String itemName = "" + sc.next();
for (int i = 0; i < store.length; i++) {
if (store[i] != null && store[i].getName().equals(itemName)) {
// Checks if the given item name is available in the store
System.out.println("We have " + store[i].getQuantity() + " " + store[i].getName() + "s in our stock. " + store[i].getBuyPrice() + " each");
System.out.println("How many would you like to buy?");
int buyQuantity = sc.nextInt();
// Checks if there is enough in the stock
if (buyQuantity > store[i].getQuantity()) {
System.out.println("Not enough " + store[i].getName() + " available in the stock.");
break;
} else {
// Checks if Player can afford it
if (Player.getInstance().getCoins() >= store[i].getBuyPrice()) {
// Update player inventory
Player.getInstance().removeCoins(buyQuantity * store[i].getBuyPrice());
Item item = store[i];
item.setQuantity(buyQuantity);
Player.getInstance().getInv().addItem(item);
// Buy transaction
store[i].setQuantity(store[i].getQuantity() - buyQuantity);
System.out.println("You have purchased " + buyQuantity + "x " + itemName);
System.out.println("Coins: " + Player.getInstance().getCoins());
// Checks if the entire amount has been bought
if (buyQuantity == store[i].getQuantity()) {
store[i] = null;
System.out.println("That's all " + itemName + " the store had");
}
break;
} else {
System.out.println("You don't have enough coins to buy " + buyQuantity + " " + itemName + "s");
break;
}
}
}
}
}
这是我的控制台输出示例:
Which item would you like to buy?
Slot 0: Weapon
Slot 1: Cake
Slot 2: Arrow
Arrow
We have 100 Arrows in our stock. 2 each
How many would you like to buy?
10
You have purchased 10x Arrow
Coins: 980
That's all Arrow the store had
我已经尝试和思考了很长一段时间,但我无法弄清楚我的错误。你有什么建议吗?我尝试调试,一切正常,值正确。但是当我输入我想购买的数量时,我的 int 输出并没有影响任何东西。非常感谢任何提示!
【问题讨论】:
标签: java debugging methods inventory-management shop