我有一个 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/