从一个文件读取内容计算出结果,将结果写入到另一个文件中

本文介绍了一个Java程序,该程序从questions.txt文件中读取简单的数学运算表达式,计算其结果,并将答案写入到results.txt文件中。涉及的技术包括Java的文件读写操作、正则表达式的使用以及基本的算术运算。

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

/*
 * 项目根路径下有个questions.txt文件内容如下:
	5+5 [ 5, 5]
	150-25
	155*155
	2555/5
	要求:读取内容计算出结果,将结果写入到results.txt文件中
 */
public class Test5 {
	public static void main(String[] args) throws IOException {
		//高效字符流来读取文件
		BufferedReader br = new BufferedReader(new FileReader("questions.txt"));
		//创建集合对象
		ArrayList<String> als = new ArrayList<String>();
		//读数据
		String line;
		while ((line =  br.readLine()) != null) {
			//我把这些读到的数据写到集合中
			als.add(line);
		}
		
		//获得集合的0号索引元素
		String str1 = als.get(0);
		//切割这个元素
		String[] split1 = str1.split("\\+");
		//String ==> int
		int result1 = Integer.parseInt(split1[0]) + Integer.parseInt(split1[1]);
		//写数据 字符输出流
		BufferedWriter bw = new BufferedWriter(new FileWriter("result.txt"));
		//那我就拼字符串
		bw.write(str1+"="+result1 + "");
		bw.newLine();
		
		//获得集合的1号索引元素
		String str2 = als.get(1);
		//切割这个元素
		String[] split2 = str2.split("\\-");
		//String ==> int
		int result2 = Integer.parseInt(split2[0]) - Integer.parseInt(split2[1]);
		//那我就拼字符串
		bw.write(str2+"="+result2 + "");
		bw.newLine();
		
		//获得集合的2号索引元素
		String str3 = als.get(2);
		//切割这个元素
		String[] split3 = str3.split("\\*");
		//String ==> int
		int result3 = Integer.parseInt(split3[0]) * Integer.parseInt(split3[1]);
		//那我就拼字符串
		bw.write(str3+"="+result3 + "");
		bw.newLine();
		
		//获得集合的3号索引元素
		String str4 = als.get(3);
		//切割这个元素
		String[] split4 = str4.split("\\/");
		//String ==> int
		int result4 = Integer.parseInt(split4[0]) / Integer.parseInt(split4[1]);
		//那我就拼字符串
		bw.write(str4+"="+result4 + "");
		bw.newLine();

		br.close();
		bw.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值