java实现计算机随机出题:随机出十道小学四则运算题目,要求操作数为10以内,运算加、减、乘、除,并可以根据用户的答案给出“√”或者“×”提示,最后计算总得分。
时间: 2024-03-16 16:48:13 浏览: 249
好的,以下是 Java 代码实现这个功能:
```java
import java.util.Random;
import java.util.Scanner;
public class RandomArithmeticQuiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int score = 0;
for (int i = 0; i < 10; i++) {
int a = random.nextInt(10) + 1;
int b = random.nextInt(10) + 1;
String operator = getRandomOperator();
int answer = calculateAnswer(a, b, operator);
System.out.print("第" + (i + 1) + "道题:" + a + " " + operator + " " + b + " = ");
int userAnswer = scanner.nextInt();
if (userAnswer == answer) {
System.out.println("你的答案:" + userAnswer + ",结果:√");
score += 10;
} else {
System.out.println("你的答案:" + userAnswer + ",结果:×");
}
}
System.out.println("你的得分是:" + score + "分");
}
public static String getRandomOperator() {
String[] operators = {"+", "-", "*", "/"};
Random random = new Random();
return operators[random.nextInt(4)];
}
public static int calculateAnswer(int a, int b, String operator) {
switch (operator) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
default:
return 0;
}
}
}
```
运行代码后,程序会随机生成十道小学四则运算题目,您需要输入答案。程序会根据您的答案给出“√”或者“×”提示,并最终计算出总得分。注意,程序只能处理整数的四则运算,如果输入了小数,程序会出错。
阅读全文