java习题生成50道100以内加减法混和习题,题中不能有相同的算式,加法和减法生成模块进行分离(更改)
时间: 2024-10-21 15:07:50 浏览: 34
在Java中生成50道100以内随机的加减混合运算习题,你可以创建两个独立的模块,分别负责生成加法和减法题目。这里是一个简单的示例:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// 加法生成模块
public class AdditionGenerator {
private static final int MAX_VALUE = 100;
public List<String> generate(int numQuestions) {
List<String> questions = new ArrayList<>();
for (int i = 0; i < numQuestions; i++) {
int a = (int) (Math.random() * MAX_VALUE);
int b = (int) (Math.random() * MAX_VALUE);
while (a == b || questions.contains(a + " + " + b)) { // 确保不重复
b = (int) (Math.random() * MAX_VALUE);
}
questions.add(String.format("%d + %d", a, b));
}
return questions;
}
}
// 减法生成模块
public class SubtractionGenerator {
private static final int MAX_VALUE = 100;
public List<String> generate(int numQuestions) {
List<String> questions = new ArrayList<>();
for (int i = 0; i < numQuestions; i++) {
int a = (int) (Math.random() * MAX_VALUE);
int b = (int) (Math.random() * MAX_VALUE);
while (a == b || questions.contains(String.format("%d - %d", a, b))) { // 确保不重复
b = (int) (Math.random() * MAX_VALUE);
}
questions.add(String.format("%d - %d", a, b));
}
return questions;
}
}
```
然后,你可以结合这两个模块来生成混合的习题集:
```java
public class Main {
public static void main(String[] args) {
int totalQuestions = 50;
AdditionGenerator addGen = new AdditionGenerator();
SubtractionGenerator subGen = new SubtractionGenerator();
List<String> additionQuestions = addGen.generate(totalQuestions / 2);
List<String> subtractionQuestions = subGen.generate(totalQuestions / 2);
List<String> mixedQuestions = new ArrayList<>(additionQuestions);
mixedQuestions.addAll(subtractionQuestions);
Collections.shuffle(mixedQuestions); // 随机排序
System.out.println("混合习题集:");
for (String question : mixedQuestions) {
System.out.println(question);
}
}
}
```
这将生成包含50道加减混合题目的列表,其中加法和减法各占一半,且每个算式都是唯一的。
阅读全文