代码:
package haxi;
import java.io.*;
public class dodo
{
public static void main(String[] args)
{
int numQuestions = 100; // 题目数量
int maxNum = 100; // 题目中最大的数字
String[] operators = {"+", "-", "*", "/"}; // 题目中可用的运算符
File YouDaAn = null;
FileWriter FwDA=null;
File meiDaAn =null;
FileWriter FwMDA=null;
try
{
// 创建带答案的题目文件
YouDaAn = new File("questions_with_answers.txt");
FwDA = new FileWriter(YouDaAn);
// 创建不带答案的题目文件
meiDaAn = new File("questions.txt");
FwMDA = new FileWriter(meiDaAn);
// 生成题目并写入文件
for (int i = 1; i <= numQuestions; i++)
{
//Math.random() * maxNum,生成一个0-maxNum之间的伪随机数
int num1 = (int) (Math.random() * maxNum) + 1;
int num2 = (int) (Math.random() * maxNum) + 1;
//Math.random() * operators.length),生成一个0-operators.length之间的伪随机数,实现随机返回一个符号
//随机进行一种计算
String operator = operators[(int) (Math.random() * operators.length)];
//生成题目
String question = num1 + " " + operator + " " + num2 + " = ";
// 计算答案
int answer;
switch (operator)
{
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
case "*":
answer = num1 * num2;
break;
case "/":
answer = num1 / num2;
break;
default:
answer = 0;
break;
}
// 将题目和答案写入文件
FwDA.write(i + ". " + "题目是:"+question + "答案是:"+answer + "\n");
FwMDA.write(i + ". " +"题目是:"+ question + "\n");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(FwDA!=null)
{FwDA.close();}
}
catch(IOException e)
{
e.printStackTrace();
}
try
{
if(FwMDA!=null)
{FwMDA.close();}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}