四则运算在线答题系统

思路:

代码功能部分分为:随机出题,打印到文件,从文件中读取,读取一个题提示输入答案,计算正确题数。

随机出题的代码 上一次四则运算已经完成此功能;

打印到文件用FileWriter函数进行写入,并设置两题目之间的分隔符号;

从文件里读取,用readLine函数进行读写,打印输出到控制台,并设置遇见分隔符则停止读入,然后提示输入答案,并将答案存储后与正确答案对比,计算正确的题目数量。

代码:

package operation;

import java.util.*;
import java.io.*;

public class SystemDemo01{
public static int rightAnswer=0;
public static void main(String[] args) {
String str = "";
FileWriter fw = null;
Random n = new Random();//随机函数
int[] a = new int[100];//存储式子序号
int[] b = new int[100];//存储第一个数
int[] c = new int[100];//存储运算符号对应的数字
int[] d = new int[100];//存储第二个数
int[] f = new int[100];//存储正确结果
//生成并存储到文件
try {
// D盘生成txt文件并存入随机数
fw = new FileWriter("D:/java1/workplace/operation/operation.txt");
for(int i = 1;i <= 100; i++){
a[i-1] = i;
b[i-1] = n.nextInt(100)+1;
int j = n.nextInt(4) + 1;
c[i-1] = j;
if(j == 2) d[i-1] = n.nextInt(b[i-1])+1;//减法第二个数字不能比第一个大
else if(j == 4) //除法结果需要为整数
{
int m = 1;
int p = 1;
while(p > 0)//判断能否被整除
{
m = n.nextInt(b[i-1])+1;
if(b[i-1]%m == 0) p = 0;
}
d[i-1] = m;
}
else d[i-1] = n.nextInt(100)+1;
switch(c[i-1])//随机出符号
{
case 1:f[i-1] = b[i-1] + d[i-1];break;
case 2:f[i-1] = b[i-1] - d[i-1];break;
case 3:f[i-1] = b[i-1] * d[i-1];break;
case 4:f[i-1] = b[i-1] / d[i-1];break;
}
}
for(int i = 1;i<=100;i++){
switch(c[i-1])//随机出符号
{
case 1:str = a[i-1] + "." + b[i-1] + "+" + d[i-1] + "=";break;
case 2:str = a[i-1] + "." + b[i-1] + "-" + d[i-1] + "=";break;
case 3:str = a[i-1] + "." + b[i-1] + "*" + d[i-1] + "=";break;
case 4:str = a[i-1] + "." + b[i-1] + "/" + d[i-1] + "=";break;
}
fw.write(str);
fw.write("\r\n");
fw.write("*******");
fw.write("\r\n");
fw.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(fw != null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


//从文件输出
try{
int i=0;
BufferedReader br = new BufferedReader(new FileReader("D:/java1/workplace/operation/operation.txt"));
String line = "";
int putAnswer;
while((line = br.readLine())!= null){
if(line.charAt(0)=='*'){
System.out.println("请输入答案:");
Scanner an=new Scanner(System.in);
putAnswer=an.nextInt();
if(putAnswer==f[i]){
rightAnswer++;
}
i++;
}
else{
System.out.println(line);
}
}
System.out.println("总共答对"+rightAnswer+"道题");
br.close();
}
catch(Exception e){
System.out.println(e.toString());
}
}

}

猜你喜欢

转载自www.cnblogs.com/zhoulonghai/p/9964748.html
今日推荐