四则运算
package 输入输出; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.BufferedReader; 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 Yunsuan { public static void main(String[] args) { String simple[]= {"+","-","*","/"}; int[] answer=new int[100]; for(int i=0;i<100;i++) {//产生30个题目 int a=(int)(Math.random()*10);//产生1-10的随机数 int b=(int)(Math.random()*10); int c=(int)(Math.random()*4); String str =a+simple[c]+b;//运算符的位置 switch(c) { case 0:answer[i]=a+b;break; case 1:answer[i]=a-b;break; case 2:answer[i]=a*b;break; case 3:{if(b==0) { do{ b=(int)(Math.random()*10); }while(b==0); answer[i]=a/b;break; } else answer[i]=a/b;break; } } try { BufferedWriter output = new BufferedWriter(new FileWriter(new File("D:\\title.txt "),true)); output.write(str+"="); output.write("\r\n"); output.close(); } catch (Exception e){//异常处理} } } File file = new File("D:\\title.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语句,第三点读取语句不熟悉,出现了问题,所以时间拖了很久