Java实验5 IO流 第三题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42623428/article/details/84593170

假设某个餐馆平时使用: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);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42623428/article/details/84593170