JAVA 8-3 菜单文件处理 (20 分)

本文介绍了一个Java程序,该程序从两个文本文件中读取菜单价格和顾客订单,然后计算并输出所有顾客消费的总价格。程序使用了HashMap来存储菜品价格,并通过BufferedReader和InputStreamReader处理文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设某个餐馆平时使用:1)文本文件(orders.txt)记录顾客的点菜信息,每桌顾客的点菜记录占一行。每行顾客点菜信息的记录格式是“菜名:数量,菜名:数量,…菜名:数量”。例如:“烤鸭:1,土豆丝:2,烤鱼:1”。2)文本文件(dishes.txt)记录每种菜的具体价格,每种菜及其价格占一行,记录格式为“菜名:价格“。例如:“烤鸭:169”。编写一个程序,能够计算出orders.txt中所有顾客消费的总价格。(注意,请使用文本读写流,及缓冲流来处理文件)

import java.io.*;
import java.util.*;
public class Menu {
	public static void main(String args[]) throws FileNotFoundException {

		Map<String, Integer> dimp = new HashMap<String, Integer>();

		try {
			File file2 = new File("C:\\程序\\JAVA\\Io\\dishes.txt");
			BufferedReader di = new BufferedReader(new InputStreamReader(new FileInputStream(file2)));
			String s = di.readLine();
			while (s != null) {
				String[] t = s.split(": ");
				if (t.length == 2) {
					dimp.put(t[0], Integer.parseInt(t[1]));
				}
				s = di.readLine();
			}
			di.close();
		} catch (Exception e) {
			System.out.println(e);
		}

		int all = 0;
		try {
			File file = new File("C:\\程序\\JAVA\\Io\\orders.txt");
			InputStreamReader Re = new InputStreamReader(new FileInputStream(file));
			BufferedReader or = new BufferedReader(Re);
			String s = or.readLine();
			while (s != null) {
				String[] s1 = s.split(", ");
				for (int i = 0; i < s1.length; i++) {
					String t2[] = s1[i].split(": ");
					if (t2[0] != null)
						all += dimp.get(t2[0]) * Integer.parseInt(t2[1]);
				}
				s = or.readLine();
			}
			or.close();
		} catch (Exception e) {
			System.out.println("路径2错误!");
		}

		System.out.println("总价格:" + all);
	}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值