java - 我怎样才能接近这台自动售货机?

标签 java loops

我有一个 Java 任务,要制作一台自动售货机,使用 printf 工具显示商品和价格,并要求用户输入他们拥有的金额。然后,它要求用户选择一个字符,如果输入 x 则退出,如果输入无效字符则提示再次尝试。它还会记录他们剩余的钱的总计,并且不允许他们购买没有钱的东西。用户 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
}

那么,你有责任填写空白。

关于java - 我怎样才能接近这台自动售货机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28656367/

相关文章:

java - log4j:使用了哪个配置文件?

java - 有没有办法将 redquerybuilder 与 Lucene 一起使用?

java - 如何比较 Struts 2 中 url 请求参数中的单个字符

java - Freemarker 迭代对象的 ArrayList 并访问变量?

c# - 遍历任务列表 C#

java - 具有缓存功能的 Http 代理 servlet

java - 无法使用 Java sqlite jdbc 从 Firefox 读取表

python - python 中的循环优化

javascript - 如何在javascript for循环中的每次迭代后延迟?

java - Break 语句会让我的代码更快吗?