【问题标题】:How can I approach this vending machine?我怎样才能接近这台自动售货机?
【发布时间】:2015-02-22 09:31:11
【问题描述】:

我有一个使用 Java 的任务来制作一台自动售货机,该自动售货机使用 printf 工具显示商品和价格,并要求用户输入他们拥有的钱。然后它要求用户使用一个字符进行选择,如果他们输入 x 则退出,如果他们输入无效字符则提示再次尝试。它还保留了他们剩下的钱的总和,并且不允许他们购买他们没有钱的东西。用户 1 完成后,下一个用户可以输入他们拥有的金额并选择一个项目,但第一个用户选择的项目不存在。这个循环重复,直到机器中没有任何东西或用户结束程序。每个用户都应该能够(一件一件地)购买任意数量的每件商品,直到该商品售罄为止。

【问题讨论】:

  • 好像用户 1 和用户 2 不能都买牛奶。那么,用户 1 可以买两个牛奶吗?
  • 是的,这意味着每个用户都可以购买任意数量的每件商品,直到没有剩余为止。

标签: java loops


【解决方案1】:

我会使用一个类来表示一种项目。

public class Item { // or without public
    private String name;
    private char choice;
    private double price;
    private int amount; // or name it *quant*-what I can't spell that word
    // Constructors, getters, setters, etc.
}

您可以使用列表来处理它们。这会初始化供应商中的项目:

List<Item> items = new ArrayList<>();
items.add(new Item("Milk", 'a', 2.00, 5));
// Add other items

这会打印所有项目:

for(Item item : items)
    System.out.printf(/* format string */, item.getName(), /* other arguments */);

这处理实际购买:

boolean foundItem = false;
for(Item item : items) {
    if(item.getChoice() == choice) {
        foundItem = true;
        // Handle not enough money, not enough amount, etc. or sell it
    }
}
if(!foundItem) {
    // Invalid entry
}

这是我们的主要内容:

public static void main(String s) {
    // Initialize items in the vender
    // Initialize other things needed
    while(/* has items to sell */) {
        // Read a double as customer's money
        // `break;` if is a program-exit request
        while(true) {
            // Print current items
            // Read a character as customer choice, to lower case
            // `break;` if is an customer-exit request
            // Handle the actual purchase request
        }
        // Print customer exit message
    }
    // Print program exit message
}

嗯,填空是你的责任。

【讨论】:

    【解决方案2】:

    您的while(choice==...) 循环似乎永远不会结束。 变量choice 在循环中永远不会改变,所以一旦你进入你就永远不会出来。 您应该提示用户在循环中输入新的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 2016-01-31
      • 2017-02-25
      • 2022-12-06
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多