日期:2014-05-20  浏览次数:20832 次

求做作业
实验内容:
1 熟悉for while do..while语句,为具体操作选择最合适的循环
实验重点:for 语句的使用
实验题目:
设计一个自动售货机,提供如下选择:
[1] Get gum
[2] Get chocolate
[3] Get popcorn
[4] Get juice
[5] Display total sold 
[6] Quit
允许用户连续的从这些选项中进行选择。当选中1-4选项时,显示适当的信息确认选项。例如当用户选择3时,可以显示如下信息:
Here is your popcorn
当用户选择5时,显示已经售出的每种商品的数量。例如:
4  items of gum sold
3 items of chocolate sold
8 items of popcorn sold
当用户选择6时,程序终止。如果输入1-6以外的选项,显示出错信息,例如:
 Error, option 1-6 only!
这个咋写呢,老师上课老砍别的,真心没学会

------最佳解决方案--------------------
测试过,没有大问题,参考一下吧

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");