1. 程式人生 > >四則運算線上答題系統

四則運算線上答題系統

思路:

程式碼功能部分分為:隨機出題,列印到檔案,從檔案中讀取,讀取一個題提示輸入答案,計算正確題數。

隨機出題的程式碼 上一次四則運算已經完成此功能;

列印到檔案用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());
}
}

}