关于文件储存-四则运算
使用BufferedWrite、File建立文件的输入输出流
编写生成随机数的函数
编写生成加减乘除符号的函数
先将生成的一百道题写入文件中,同时将这一百道题的结果存入数组中,再将文件中的运算题一道一道读入到控制台中, 用户输入答案,与标准答案比较,
若正确,分数计数器加一,若错误,错误计数器加一,将其输入答案的语句和判断语句放入try-catch语句中,若检测到输入异常,跳出出题循环,输出分数及错题数
package suiji_fouroperation_100; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Fourqperaction { public static int produceNum() { int temp; temp = (int)(Math.random()*100); return temp; } public static String produceChar() { String[] zf = new String[]{"+", "-", "*", "/"}; String temp1; int temp2; temp2 = (int)(Math.random()*3); temp1 = zf[temp2]; return temp1; } @SuppressWarnings("resource") public static void main(String[] args) throws IOException { int i; int k1; int k2; int[] an = new int[100];//存答案 String s; Scanner in = new Scanner(System.in); int uan; int score = 0; int fals = 0; File file = new File("Text.txt"); if (!file.exists()) {// 如果文件不存在则创建 file.createNewFile(); } // 获取该文件的缓冲输出流 BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file)); for(i = 0; i < 100; i++) { k1 = produceNum(); k2 = produceNum(); s = produceChar(); if(s.compareTo("-") == 0) { if(k1 < k2) { int temp; temp = k1; k1 = k2; k2 = temp; } an[i] = k1 - k2; } else if(s.compareTo("+") == 0) { an[i] = k1 + k2; } else if(s.compareTo("*") == 0) { an[i] = k1 * k2; } else if(s.compareTo("/") == 0) { int temp = k1; k1 = temp * k2; if(k2 == 0) { k2++; k1 = temp * k2; } an[i] = temp; } String k11, k22; k11 = k1+""; k22 = k2+""; bufferedWriter.write(k11+s+k22+"="); bufferedWriter.newLine();// 表示换行 bufferedWriter.write("***********************"); bufferedWriter.newLine();// 表示换行 bufferedWriter.flush();// 清空缓冲区 //bufferedWriter.close();// 关闭输出流 } BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); String line = "";// 用来保存每次读取一行的内容 String stop = "0"; i = 0; while (((line = bufferedReader.readLine()) != null)||(stop.compareTo("*") == 0)||(i <= 99)) { System.out.println(line); line = bufferedReader.readLine(); System.out.println(line); try { uan = in.nextInt(); if(uan == an[i]) { System.out.println("正确"); System.out.print("\n"); score++; } else { System.out.println("错误,正确结果为"+an[i]); System.out.print("\n"); fals++; } } catch(Exception e) { break; } i++; } System.out.println("得分为"+score+"分"+",做错题数为"+fals+"道"); bufferedReader.close();// 关闭输入流 } }