四则运算答题版
用了好长好长时间。。。。
从下午2:00上课到5:25下了课,吃过饭在宿舍还整了得有一个小时
加一块儿将近五个小时,天啊!!!
源代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Random;
import java.util.Scanner;
public class SZYSfile {
public static void main(String args[])throws IOException,ClassNotFoundException {
File f = new File("C:\\Users\\刘世朝\\Desktop\\Test.txt");
f.createNewFile();
FileOutputStream fis = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(fis);
int[] answer = new int [100];//存答案
for(int i = 0 ; i < 100;i++) {
int a = new Random().nextInt(10);//随机数a
int b = new Random().nextInt(10);//随机数b
int suijifu = new Random().nextInt(4);//随机运算符
String symbol=" ";
switch(suijifu) {
case(0):
{symbol = "+";answer[i]=a+b; break;}
case(1):
{symbol = "-";answer[i]=a-b; break;}
case(2):
{symbol ="×";answer[i]=a*b; break;}
case(3):
if(b==0) { symbol = "+";answer[i]=a+b; break;}
else
if(a%b!=0) {symbol = "-";answer[i]=a-b; break;}
else
if(a%b==0) {symbol = "÷";answer[i]=a/b; break;}
}
osw.write(a+symbol+b+"=");
osw.write("\r\n");
}
osw.close();
//读取文件中的运算
File file = new File("C:\\Users\\刘世朝\\Desktop\\Test.txt");
int i=0;
int score = 0;
if(file.exists()){
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String lineContent = null;
while((lineContent = br.readLine())!=null){
System.out.println(lineContent);
Scanner input = new Scanner(System.in);
int a=input.nextInt();
if(a==answer[i]) {
System.out.println("回答正确!");
score++;
}
else
{System.out.println("回答错误! 答案是"+answer[i]);}
i++;
}
br.close();
fileReader.close();
} catch (FileNotFoundException e1) {
System.out.println("no this file");//文件不存在抛异常
e1.printStackTrace();
} catch (IOException e1) {
System.out.println("io exception");
e1.printStackTrace();
}
} System.out.println("分数为:"+score);
}
}
截图:
问题:
首先是四则运算进一步完善了一下,随机输出字符串,打乱+ - * ÷的顺序。
然后是将四则运算题目输出到txt文本文件中,改过之后是用File的输出。
最后是怎样判断答案对错,运用两个数组对比,一个存答案,一个从数据台输入,然后再输入到文本文件中。