四則運算答題版
用了好長好長時間。。。。
從下午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的輸出。
最後是怎樣判斷答案對錯,運用兩個陣列對比,一個存答案,一個從資料臺輸入,然後再輸入到文字檔案中。