Java – 购物系统中的错误

huangapple go评论90阅读模式
英文:

Java - Bug in Shop System

问题

Sure, here's the translated code portion:

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;
                }
            }
        }
    }
}

And the translated console output:

Which item would you like to buy?
Slot 0: 武器
Slot 1: 蛋糕
Slot 2: 箭头
箭头
我们库存中有 100 支箭头。每支售价 2
您想购买多少支?
10
您已购买 10 支箭头
剩余金币:980
这是库存中所有的箭头

If you have any questions or need further assistance, feel free to ask!

英文:

so I have a little inventory/shop interaction which is I can't find a solution for.

The player is supposed to be able to buy and sell items with a predefined buy/sell value in my Item class constructor. With the help of a scanner I'm able to sell without any bugs. However if I buy any quantity, the entire quantity is bought somehow. The item quantity is set to 0 after I buy any quantity once.

	private void buyItem() {
System.out.println(&quot;Which item would you like to buy?&quot;);
showStock();
@SuppressWarnings(&quot;resource&quot;)
Scanner sc = new Scanner(System.in);
String itemName = &quot;&quot; + sc.next();
for (int i = 0; i &lt; store.length; i++) {
if (store[i] != null &amp;&amp; store[i].getName().equals(itemName)) {
// Checks if the given item name is available in the store
System.out.println(&quot;We have &quot; + store[i].getQuantity() + &quot; &quot; + store[i].getName() + &quot;s in our stock. &quot; + store[i].getBuyPrice() + &quot; each&quot;);
System.out.println(&quot;How many would you like to buy?&quot;);
int buyQuantity = sc.nextInt();
// Checks if there is enough in the stock
if (buyQuantity &gt; store[i].getQuantity()) {
System.out.println(&quot;Not enough &quot; + store[i].getName() + &quot; available in the stock.&quot;);
break;
} else {
// Checks if Player can afford it
if (Player.getInstance().getCoins() &gt;= 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(&quot;You have purchased &quot; + buyQuantity + &quot;x &quot; + itemName);
System.out.println(&quot;Coins: &quot; + Player.getInstance().getCoins());
// Checks if the entire amount has been bought
if (buyQuantity == store[i].getQuantity()) {
store[i] = null;
System.out.println(&quot;That&#39;s all &quot; + itemName + &quot; the store had&quot;);
}
break;
} else {
System.out.println(&quot;You don&#39;t have enough coins to buy &quot; + buyQuantity + &quot; &quot; + itemName + &quot;s&quot;);
break;
}
}
}
}
}

And this is my console output from an example:

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&#39;s all Arrow the store had

I've been trying and thinking for quite some time, but I can't figure out my bug. Do you have any suggestions? I tried debugging and everything was "working" the values were correct. But when I entered the quantity I would like to buy, my int output didn't affect anything. Would highly appreciate any tip!

答案1

得分: 2

以下是翻译的内容:

这一行代码:

Item item = store[i];

不会创建副本,而是引用存储在数组store中的同一对象。接下来的代码:

item.setQuantity(buyQuantity);

store中项目的数量设置为buyQuantity,然后以下代码:

store[i].setQuantity(store[i].getQuantity() - buyQuantity);

有效地减少了项目的计数到0(在商店和玩家库存中都是如此)。

至于修复方法,可以使用clone(),但这被视为有问题。我建议采用语义上不同的方法。每个项目不代表一个单一的项目,而是一组项目的捆绑。为了使这可行,我会使通用的超类Item(我假设已存在)成为T extends Item&lt;T&gt;的泛型,abstract并给它一个public abstract T take(int amount);方法:

public abstract class Item&lt;T extends Item&lt;T&gt;&gt; {
    ...
    public abstract T take(int amount);
    ...
}

然后,我会更改所有子类以扩展这个超类,例如:

public class Arrow extends Item&lt;Arrow&gt; {
    public Arrow take(int amount) {
        ...
    }
}

最后,我会重命名类以清楚地反映每个“Item”都是一组项目。例如,可以将“Item”重命名为“ItemBundle”,将“Arrow”重命名为“ArrowBundle”或“Arrows”。

英文:

The line

Item item = store[i];

does not create a copy, but references the same object as is stored in the array store. The following

item.setQuantity(buyQuantity); 

sets the quantity of the item in the store to buyQuantity and the following

store[i].setQuantity(store[i].getQuantity() - buyQuantity);

effectively reduces the count of the item to 0 (both in the store and in the player inventory).

As for the fix, one could use clone() but this is regarded as broken.

I would suggest a semantically different approach. Each item does not represent a single item, but a bundle of items. Thus, a specific amount can be added or removed to/from the bundle. For this to be feasible, I would make the common superclass Item (which I assume exists) generic in T extends Item&lt;T&gt;, abstract and give it a public abstract T take(int amount); method:

public abstract class Item&lt;T extends Item&lt;T&gt;&gt; {
...
public abstract T take(int amount);
...
}

Then, I would change all subclasses to extend this superclass, e.g.

public class Arrow extends Item&lt;Arrow&gt; {
public Arrow take(int amount) {
...
}
}

Finally, I would rename the classes to reflect clearly that each Item is a bundle of items. E.g., Item can be renamed to ItemBundle and Arrow can be renamed to ArrowBundle or Arrows.

答案2

得分: 1

你在这里明确地更改了购买物品的数量,将其更改为玩家所请求的数量:

Item item = store[i];
item.setQuantity(buyQuantity);

如果你想要将 x 个数量的 Item 添加到玩家的库存中,你需要创建一个新的 Item 实例,然后设置其 buyQuantity 为购买的数量。这样你就能保持商店库存的完整性。

英文:

You are explicitly changing the quantity of the purchased item to the amount requested by the player here:

Item item = store[i];
item.setQuantity(buyQuantity);

If you want to add x amount of Item the the player's inventory you need to create a new instance of that Item on which you set the buyQuantity to whatever amount was purchased. That way you keep the integrity of the store's stock.

huangapple
  • 本文由 发表于 2020年8月13日 03:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63383618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定