1. 程式人生 > >100道題的程式碼

100道題的程式碼

完成時間:15:40

package Class_fifth;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.Scanner;

public class The_Class_Test {

    //隨機生成100道題目
public void scanf() throws IOException { String str[]=new String[100]; String answer[]= new String[100]; int n = 0; int x,y,m,mm; Random random = new Random(System.currentTimeMillis()); String ch[] = new String[] {"-","+","/","*"}; for(int i = 1;i<=100;i++) { x
= random.nextInt(100)+1; y = random.nextInt(100)+1; m = random.nextInt(20); mm = random.nextInt(4); if(ch[mm]=="*"){ str[n]= x+"*"+y+"="; answer[n]=x*y+"";} if(ch[mm]=="/"){ str[n]
= x*m+ch[mm]+x+"="; answer[n]=m+""; } if(ch[mm]=="+"){ str[n] = x+"+"+y+"="; answer[n]=x+y+""; } if(ch[mm]=="-") { if(x>y) str[n]= x+"-"+y+"="; else str[n]= y+"-"+x+"="; answer[n]=Math.abs(x-y)+""; } n++; } //將題目輸入test.txt文字中 FileWriter fw = null; try { //建立字元輸出流 fw = new FileWriter("test.txt"); for(int i = 0;i<100;i++) fw.write(str[i]+"\r\n"); } catch (IOException ioe) { ioe.printStackTrace(); } finally { //使用finally塊來關閉檔案輸出流 if (fw != null) { fw.close(); } } //將答案新增到answer.text文字中 FileWriter fwas = null; try { //建立字元輸出流 fwas = new FileWriter("answer.txt"); for(int i = 0;i<100;i++) fwas.write(answer[i]+"\r\n"); } catch (IOException ioe) { ioe.printStackTrace(); } finally { //使用finally塊來關閉檔案輸出流 if (fwas != null) { fwas.close(); } } } public void print() throws IOException { //輸出題目進入控制檯 String str[]= new String[100]; int n =0; File a=new File("test.txt"); FileInputStream b = new FileInputStream(a); InputStreamReader c=new InputStreamReader(b,"UTF-8"); { BufferedReader bufr =new BufferedReader(c); String line = null; while((line = bufr.readLine())!=null){ str[n]=line; n++; } bufr.close(); } c.close(); b.close(); //把答案放進字串陣列中 String answer[]= new String[100]; n =0; File as=new File("answer.txt"); FileInputStream bs = new FileInputStream(as); InputStreamReader cs=new InputStreamReader(bs,"UTF-8"); { BufferedReader bufrs =new BufferedReader(cs); String lines = null; while((lines = bufrs.readLine())!=null){ answer[n]=lines; n++; } bufrs.close(); } cs.close(); bs.close(); //輸出題目,並設定輸出的格式 Scanner cin = new Scanner(System.in); int score =0; for(int i=0;i<100;i++) { String Answer; System.out.println(str[i]); Answer = cin.nextLine(); if(Answer.equals("*")) { System.out.println("您一共做了"+i+"道題"); System.out.println("您做錯"+(i-score)+"題"); System.out.println("您做對"+score+"題"); System.exit(0); } else { if(Answer.equals(answer[i])) score++; } } } public static void main(String[] args) throws IOException { The_Class_Test a = new The_Class_Test(); a.scanf(); a.print(); } }