Java输出50道100以内加减法,并编写测试代码
时间: 2024-05-11 22:13:38 浏览: 196
以下是Java输出50道100以内加减法的代码:
```java
import java.util.Random;
public class MathQuiz {
public static void main(String[] args) {
Random random = new Random();
int num1, num2;
char operator;
int correctCount = 0;
int wrongCount = 0;
for (int i = 1; i <= 50; i++) {
num1 = random.nextInt(100);
num2 = random.nextInt(100);
operator = random.nextInt(2) == 0 ? '+' : '-';
int answer = 0;
if (operator == '+') {
answer = num1 + num2;
} else {
answer = num1 - num2;
}
System.out.print(i + ". " + num1 + " " + operator + " " + num2 + " = ");
// 用户输入答案
int userAnswer = new java.util.Scanner(System.in).nextInt();
// 判断用户答案是否正确
if (userAnswer == answer) {
System.out.println("回答正确!");
correctCount++;
} else {
System.out.println("回答错误!");
wrongCount++;
}
}
System.out.println("答题结束!共回答了 " + (correctCount + wrongCount) + " 题,其中回答正确 " + correctCount + " 题,回答错误 " + wrongCount + " 题。");
}
}
```
以下是测试代码,可以在命令行中运行:
```java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
public class MathQuizTest {
@org.junit.Test
public void testMain() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
String expectedOutput = "";
int correctCount = 0;
int wrongCount = 0;
// 模拟用户输入
String input = "";
for (int i = 1; i <= 50; i++) {
int num1 = (int) (Math.random() * 100);
int num2 = (int) (Math.random() * 100);
char operator = Math.random() > 0.5 ? '+' : '-';
int answer = operator == '+' ? num1 + num2 : num1 - num2;
int userAnswer = (int) (Math.random() * 200);
input += userAnswer + System.lineSeparator();
expectedOutput += i + ". " + num1 + " " + operator + " " + num2 + " = ";
if (userAnswer == answer) {
expectedOutput += "回答正确!" + System.lineSeparator();
correctCount++;
} else {
expectedOutput += "回答错误!" + System.lineSeparator();
wrongCount++;
}
}
// 运行程序
System.setIn(new java.io.ByteArrayInputStream(input.getBytes()));
MathQuiz.main(new String[]{});
// 对比输出结果
String actualOutput = outContent.toString();
assertEquals(expectedOutput, actualOutput);
// 对比回答正确和回答错误的数量
int actualCorrectCount = actualOutput.split("回答正确!").length - 1;
assertEquals(correctCount, actualCorrectCount);
int actualWrongCount = actualOutput.split("回答错误!").length - 1;
assertEquals(wrongCount, actualWrongCount);
}
}
```
阅读全文