四则运算
实验要求
1.随机出若干算术题,存储到文件Test.txt内。
2.读取文件Test.txt内容,依次将题输出到控制台上。当用户答完一道题,下一题才会出现,中间用“*****************”分隔。
源代码
/* * 班级:信1705-1 * 学号:20173458 * 姓名:王嘉梁 */ package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.Scanner; public class Arithmetic { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); System.out.print("请输入要生成的题目数量:"); int num = sc.nextInt(); produce(num); test(); } public static void produce(int num) throws IOException { int number1; int number2; int symbol; //0代表加,1代表减,2代表乘,3代表除 BufferedWriter bw = new BufferedWriter(new FileWriter("Test.txt")); for(int i=1;i<=num;i++) { number1 = new Random().nextInt(100); number2 = new Random().nextInt(100); symbol = new Random().nextInt(4); double answer = 0; while(number2 == 0) number2 = new Random().nextInt(100); bw.write(i + "、 " + number1); switch(symbol) { case 0:bw.write("+"); answer = number1 + number2; break; case 1:bw.write("-"); answer = number1 - number2; break; case 2:bw.write("×"); answer = number1 * number2; break; case 3:bw.write("÷"); answer = (double)Math.round((double)number1/(double)number2*100)/100; break; } bw.write(number2 + "= " + answer); bw.newLine(); bw.write("***************************"); bw.newLine(); bw.flush(); } bw.close(); } public static void test() throws IOException { BufferedReader br = new BufferedReader(new FileReader("Test.txt")); Scanner sc = new Scanner(System.in); int all = 0, count = 0; String t = ""; double result; String str; while((str = br.readLine()) != null) { all++; String[] a = str.split(" "); System.out.print(a[0] + a[1]); result = sc.nextDouble(); if(result == Double.parseDouble(a[2])) count ++; else t += a[0]; str = br.readLine(); System.out.println(str); } br.close(); System.out.println("共有" + all + "道题,做对了" + count + "道。"); if(t != "") System.out.println("做错的题有:" + t.substring(0, t.length()-1)); } }
总结
读文件时出现了一个小问题,开始时while里的判断条件我写的是(str = br.readLine()) != "",所以读取最后一行(即一个空行)时出现了问题,后来将""改为了null成功解决了问题。其次出现的问题是计算除法正确结果时总是得不到正确的四舍五入保留两位后的小数,后来发现是我在变量answer放大100倍四舍五入取整后缩小时忘了强制转化为double类型。