1. 程式人生 > >Java實驗5 IO流 第三題

Java實驗5 IO流 第三題

假設某個餐館平時使用:1)文字檔案(orders.txt)記錄顧客的點菜資訊,每桌顧客的點菜記錄佔一行。每行顧客點菜資訊的記錄格式是“菜名:數量,菜名:數量,…菜名:數量”。例如:“烤鴨:1,土豆絲:2,烤魚:1”。2)文字檔案(dishes.txt)記錄每種菜的具體價格,每種菜及其價格佔一行,記錄格式為“菜名:價格“。例如:“烤鴨:169”。編寫一個程式,能夠計算出orders.txt中所有顧客消費的總價格。 

import java.io.*;
import java.util.*;
public class order {
	public static List<String> readOrder(String name) {
		List<String> data= new ArrayList<String>();
		try {
			File file=new File(name);
			BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String s=null;
			while(true) {
				s=in.readLine();
				if(s!=null)data.add(s);
				else break;
			}
			in.close();
		} catch (Exception e) {
			System.out.println("路徑錯誤");
		}
		return data;
	}
	public static Map<String,Integer> countDishes(List<String>data){
		Map<String,Integer>mp=new HashMap<String,Integer>();
		for(int i=0;i<data.size();i++) {
			String[]temp=data.get(i).split(":");
			if(temp.length==2) {
				mp.put(temp[0], Integer.parseInt(temp[1]));
			}
		}
		return mp;
	}
	public static Map<String,Integer> countorders(List<String>data){
		String[] t1=null;
		String[] t2=null;
		Map<String,Integer>mp=new HashMap<String,Integer>();
		for(int i=0;i<data.size();i++) {
			t1=data.get(i).split(",");
			for(int j=0;j<t1.length;j++) {
				t2=t1[j].split(":");
				if(t2.length==2) {
					if(mp.get(t2[0])!=null)mp.put(t2[0], Integer.parseInt(t2[1]+mp.get(t2[0])));
					else mp.put(t2[0], Integer.parseInt(t2[1]));
				}
			}
		}
		return mp;
	}
}
import java.util.*;
public class Main {

	public static void main(String[] args) {		
		List<String> orders=order.readOrder("orders.txt");
		List<String> dishes=order.readOrder("dishes.txt");
		Map<String,Integer> ordersmenu=order.countorders(orders);
		Map<String,Integer> dishesmenu=order.countDishes(dishes);
		int totalprice=0;
		int dishesprice=0;
		String name=null;
		for(Map.Entry<String, Integer>it:ordersmenu.entrySet()) {
			name=it.getKey();
			dishesprice=it.getValue();
			totalprice+=dishesmenu.get(name)*dishesprice;
		}
		System.out.println("總消費為:"+totalprice);
	}
}