日期:2014-05-20 浏览次数:20899 次
package com.pyh.demo1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Demo1 {
private Map<String, Integer> products;
/**
* 构造方法初始化数据
*/
public Demo1() {
products = new HashMap<String, Integer>();
products.put("gum", 0);
products.put("chocolate", 0);
products.put("popcorn", 0);
products.put("juice", 0);
}
/**
* 获取键盘输入的数据
* @return
*/
public int getInfo() {
System.out.print("请输入:");
String info = null;
BufferedReader read = null;
try {
read = new BufferedReader(new InputStreamReader(System.in));
info = read.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (info.matches("\\d+")) {
return Integer.parseInt(info);
} else {
return 0;
}
}
/**
* 打印菜單
*/
public void print() {
System.out.println("----------菜单开始---------");
System.out.println("[1] Get gum");
System.out.println("[2] Get chocolate");
System.out.println("[3] Get popcorn");
System.out.println("[4] Get juice");
System.out.println("[5] Display total sold");
System.out.println("[6] Quit");
System.out.println("----------菜单结束----------");
}
/**
* 循环购买商品
*/
public void gen() {
while (true) {
print();
int id = getInfo();
switch (id) {
case 1: {
System.out.println("Here is your popcorn");
products.put("gum", products.get("gum") + 1);
break;
}
case 2: {
System.out.println("Here is your chocolate");
products.put("chocolate", products.get("chocolate") + 1);
break;
}
case 3: {
System.out.println("Here is your popcorn");
products.put("popcorn", products.get("popcorn") + 1);
break;
}
case 4: {
System.out.println("Here is your juice");
products.put("juice", products.get("juice") + 1);
break;
}
case 5: {
for (String str : products.keySet()) {
System.out.println(products.get(str) + " items of " + str
+ " sold");