今天完成软件构造作业,写一个自动出题程序。
package 软件构造;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Test {
private static final int MIN_NUMBER = 1; // 最小数字范围
private static final int MAX_NUMBER = 100; // 最大数字范围
private static final int OPERATOR_ADD = 0; // 加法运算符
private static final int OPERATOR_SUBTRACT = 1; // 减法运算符
private static final int OPERATOR_MULTIPLY = 2; // 乘法运算符
private static final int OPERATOR_DIVIDE = 3; // 除法运算符
private static final String[] OPERATORS = {"+", "-", "*", "/"}; // 运算符数组
private Map<String, Integer> generatedProblems; // 存储已生成的题目
public Test() {
generatedProblems = new HashMap<>();
}
public String generateProblem() {
Random random = new Random();
String problem;
int result;
do {
int number1 = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
int number2 = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
int operatorIndex = random.nextInt(OPERATORS.length);
String operator = OPERATORS[operatorIndex];
problem = number1 + " " + operator + " " + number2;
result = calculateResult(number1, number2, operator);
} while (generatedProblems.containsKey(problem));
generatedProblems.put(problem, result);
return problem;
}
private int calculateResult(int number1, int number2, String operator) {
int result = 0;
switch (operator) {
case "+":
result = number1 + number2;
break;
case "-":
result = number1 - number2;
break;
case "*":
result = number1 * number2;
break;
case "/":
result = number1 / number2;
break;
}
return result;
}
public static void main(String[] args) {
Test generator = new Test();
for (int i = 1; i < 51; i++) {
String problem = generator.generateProblem();
System.out.println("题目"+ i+":"+problem+"=");
}
}
}