java实现计算机随机出题:随机出一道小学四则运算题目,要求操作数为10以内运算加、减、乘、除,并可以根据用户的答案给出“正确”或“错误”的提示信息。
时间: 2024-02-07 14:04:07 浏览: 80
好的,以下是一个简单的 Java 代码示例:
```java
import java.util.Scanner;
import java.util.Random;
public class ArithmeticQuiz {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
while (true) {
// 随机生成两个10以内的整数和一个运算符
int x = random.nextInt(10) + 1;
int y = random.nextInt(10) + 1;
int operatorIndex = random.nextInt(4);
char operator;
switch (operatorIndex) {
case 0:
operator = '+';
break;
case 1:
operator = '-';
break;
case 2:
operator = '*';
break;
default:
operator = '/';
break;
}
// 计算正确答案
int answer;
switch (operator) {
case '+':
answer = x + y;
break;
case '-':
answer = x - y;
break;
case '*':
answer = x * y;
break;
default:
answer = x / y;
break;
}
// 提示用户输入答案
System.out.print(x + " " + operator + " " + y + " = ");
int userAnswer = sc.nextInt();
// 判断用户答案是否正确,并输出提示信息
if (userAnswer == answer) {
System.out.println("正确!");
} else {
System.out.println("错误!");
}
// 询问用户是否继续
System.out.print("是否继续?(y/n)");
String choice = sc.next();
if (!choice.equalsIgnoreCase("y")) {
break;
}
}
sc.close();
}
}
```
希望这个 Java 代码示例能够帮到您!
阅读全文