1. 程式人生 > >11-15課堂測試

11-15課堂測試

/*
 * 信1705-2 謝培龍 20173611
 */
package 自主出題;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
import java.util.Scanner;

public class Test{
    public static String s3;
    public void writeToFile(String data){//寫入
         byte[] sourceByte = data.getBytes();
         String path 
= "D:"; String fileName = "test.txt"; if(null != sourceByte){ try { File file = new File(path+fileName);//檔案路徑(路徑+檔名) if (!file.exists()) { //檔案不存在則建立檔案,先建立目錄 File dir = new File(file.getParent()); dir.mkdirs(); file.createNewFile(); } FileOutputStream outStream
= new FileOutputStream(file); //檔案輸出流將資料寫入檔案 outStream.write(sourceByte); outStream.close(); } catch (Exception e) { e.printStackTrace(); // do something } finally { // do something } } }
public static void main(String[] args){ int grade=0; Test l=new Test(); System.out.println("輸入題數:"); Scanner in=new Scanner(System.in); int a1=in.nextInt(); StringBuffer f = new StringBuffer(); for(int i=0;i<a1;i++) { Random a=new Random(); int q=a.nextInt(100); Random b=new Random(); int w=b.nextInt(100); char c = 0; int sum=0; int x=(int)Math.floor(Math.random()*4+1); if(x==1) { c='+' ;sum=q+w; } if(x==2) { c='-' ; sum=q-w;} if(x==3) { c='*' ; sum=q*w;} if(x==4) { c='/'; sum=q/w; } System.out.println(q); System.out.println(c); System.out.println(w); System.out.println("="); Scanner result=new Scanner(System.in); int r=result.nextInt(); if(r==sum) { System.out.println("恭喜答對了! "); grade=grade+1;} else System.out.println("很遺憾 答錯了! "); String s=String.valueOf(q); String s1=String.valueOf(c); String s2=String.valueOf(w); String s0=String.valueOf(sum); String s5=s+s1+s2+"="+s0+"*"+"\t"; s3 =s5+s3; } System.out.println("答對了"+grade+"道題"); l. writeToFile(s3); } }

四則運算測試題

一道一道題輸出判斷對錯

並將題目及正確答案輸出到文字文件