请用Java帮我写一个模块化分离的0-100的随机50道加减法并得出答案,要求答案小于100,算式不重复,输出界面整齐排序,每行5个算式,并给代码注释
时间: 2024-10-22 10:12:33 浏览: 11
在Java中,我们可以使用`Random`类生成随机数,结合ArrayList来存储不重复的算式,然后利用`StringBuilder`构建整洁的输出格式。下面是一个简单的示例代码:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class RandomMathProblems {
private static final int LIMIT = 100;
private static final String[] OPERATORS = {"+", "-"}; // 加减运算符
public static void main(String[] args) {
ArrayList<String> problems = new ArrayList<>();
generateUniqueMathProblems(problems, LIMIT);
printProblemsSorted(problems);
}
// 生成指定数量的不重复加减法算式
private static void generateUniqueMathProblems(ArrayList<String> problems, int numProblems) {
Random random = new Random();
while (problems.size() < numProblems) { // 避免重复
int a = random.nextInt(LIMIT) + 1; // 保证a > 0
int b = random.nextInt(LIMIT - a + 1) + a; // 防止b大于a
String operator = OPERATORS[random.nextInt(OPERATORS.length)];
String problem = String.format("%d %s %d", a, operator, b); // 格式化算式
if (!problems.contains(problem)) {
problems.add(problem);
}
}
}
// 输出算式数组,每行5个,排序并美观显示
private static void printProblemsSorted(ArrayList<String> problems) {
StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < problems.size(); i++) {
if ((i + 1) % 5 == 0 || i == problems.size() - 1) { // 每行结束或最后一行
outputBuilder.append("\n");
}
outputBuilder.append(problems.get(i)).append(" ");
}
System.out.println(outputBuilder.toString().trim()); // 打印结果并去除多余的空格
}
}
```
阅读全文