我会使用一个类来表示一种项目。
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
}
嗯,填空是你的责任。