private static void menu1_2(int index) { System.out.println("您选择了:"+index+menu2[2][index]); if(index==0) return; try { ExerciseFiles.generateExercises(); } catch (IOException e) { e.printStackTrace(); } if(index==1){ } if(index==2){ } }在以上函数中的if(index==1){ } 实现对已有用算式基产生的加法习题文件文件进行读入然后将每个算式挨个输出,并且能从键盘中输入答案,然后将答案进行保存进自己定义名称的文件,最后在if(index==2){}中实现对刚才的文件进行批改,对于以上要求用java语言实现
时间: 2024-03-19 17:41:28 浏览: 75
实验1 类和对象的实验.doc
可以通过以下代码实现:
if (index == 1) {
try {
// 读取文件
BufferedReader br = new BufferedReader(new FileReader("加法习题.txt"));
String line;
int count = 1;
// 逐行输出算式并保存答案
PrintWriter pw = new PrintWriter(new FileWriter("答案.txt"));
while ((line = br.readLine()) != null) {
System.out.print(count + ". " + line + " = ");
int answer = new Scanner(System.in).nextInt();
pw.println(count + ". " + line + " = " + answer);
count++;
}
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
在if(index==2){}中实现文件批改可以通过以下代码实现:
if (index == 2) {
try {
// 读取文件
BufferedReader br1 = new BufferedReader(new FileReader("加法习题.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("答案.txt"));
String line1, line2;
int count = 1, correct = 0, wrong = 0;
// 逐行比较答案
while ((line1 = br1.readLine()) != null && (line2 = br2.readLine()) != null) {
if (line2.endsWith(line1.substring(line1.lastIndexOf("=") + 2))) {
System.out.println(count + ". " + line1 + " √");
correct++;
} else {
System.out.println(count + ". " + line1 + " ×");
wrong++;
}
count++;
}
System.out.println("共" + (count - 1) + "道题,答对" + correct + "道,答错" + wrong + "道");
br1.close();
br2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
需要注意的是,以上代码只是基本实现,还可以根据实际需求进行修改和完善。
阅读全文