四则运算

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("D:\\","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("D:\\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);

    }
}
结果

 

一开始没用case语句,只能打印出题目,并不能保存结果和判断对错,通过网上的学习和同学的帮助,最后完成了

posted @ 2018-11-15 21:47  呵呵刀呵呵  阅读(119)  评论(0编辑  收藏  举报