帮我生成一个小学四则运算的Java程序
![帮我生成一个小学四则运算的Java程序 帮我生成一个小学四则运算的Java程序](https://img.cveoy.top/0/23A389A805204708D78462C70BC8399A.webp)
以下是一个简单的小学四则运算Java程序,可以根据需要进行修改和优化:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
int a, b, result, answer, operator;
int correctCount = 0, wrongCount = 0;
String[] operators = {"+", "-", "*", "/"};
while (true) {
a = random.nextInt(100) + 1;
b = random.nextInt(100) + 1;
operator = random.nextInt(4);
result = calculate(a, b, operator, operators);
System.out.print(a + " " + operators[operator] + " " + b + " = ");
answer = input.nextInt();
if (answer == result) {
System.out.println("恭喜你,答对了!");
correctCount++;
} else {
System.out.println("很遗憾,答错了!");
wrongCount++;
}
System.out.println("你已经做对了" + correctCount + "道题,做错了" + wrongCount + "道题。");
System.out.println("是否继续答题?(Y/N)");
String choice = input.next();
if (choice.equalsIgnoreCase("N")) {
System.out.println("谢谢参与,再见!");
break;
}
}
}
public static int calculate(int a, int b, int operator, String[] operators) {
int result = 0;
switch (operator) {
case 0:
result = a + b;
break;
case 1:
result = a - b;
break;
case 2:
result = a * b;
break;
case 3:
result = a / b;
break;
}
return result;
}
}
该程序会随机生成两个数和一个运算符,然后要求用户输入答案,判断是否正确,并统计做对和做错的题目数量。用户可以选择继续答题或退出程序。
原文地址: https://gggwd.com/t/topic/bNuy 著作权归作者所有。请勿转载和采集!