用Java实现一个程序:
随机生成30道小学二年级的四则运算,要求:减法结果不可出现负数,除法结果不可出现小数,乘法结果不能超过999.
代码如下:
import java.util.Random;标签:random,operand1,operand2,int,9.19,System,随笔,out From: https://www.cnblogs.com/my0326/p/17715895.html
import java.util.Scanner;
public class ArithmeticQuiz {
public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int correctCount = 0;
int wrongCount = 0;
for (int i = 0; i < 30; i++) {
int operand1 = generateNumber(10, 99, random);
int operand2 = generateNumber(10, 99, random);
char op = generateOperator(random);
int result = 0;
String operatorStr;
switch (op) {
case '+':
result = operand1 + operand2;
operatorStr = "+";
break;
case '-':
if (!checkSubtraction(operand1, operand2)) {
i--;
continue;
}
result = operand1 - operand2;
operatorStr = "-";
break;
case '*':
if (!checkMultiplication(operand1, operand2)) {
i--;
continue;
}
result = operand1 * operand2;
operatorStr = "*";
break;
case '/':
if (!checkDivision(operand1, operand2)) {
i--;
continue;
}
result = operand1 / operand2;
operatorStr = "/";
break;
default:
operatorStr = "";
break;
}
System.out.println("倒计时开始!请在10秒内回答问题!");
System.out.print("题目" + (i + 1) + ": " + operand1 + " " + operatorStr + " " + operand2 + " = ");
int answer = scanner.nextInt();
Thread timerThread = new Thread(new TimerThread());
timerThread.start();
timerThread.join(10000);
timerThread.interrupt();
if (answer == result) {
System.out.println("回答正确!");
correctCount++;
} else {
System.out.println("回答错误!");
wrongCount++;
}
}
System.out.println("回答正确的题目数量: " + correctCount);
System.out.println("回答错误的题目数量: " + wrongCount);
}
public static int generateNumber(int min, int max, Random random) {
return min + random.nextInt(max - min + 1);
}
public static char generateOperator(Random random) {
char[] operators = {'+', '-', '*', '/'};
int index = random.nextInt(4);
return operators[index];
}
public static boolean checkSubtraction(int operand1, int operand2) {
return operand1 >= operand2;
}
public static boolean checkMultiplication(int operand1, int operand2) {
return operand1 * operand2 <= 999;
}
public static boolean checkDivision(int operand1, int operand2) {
return operand1 % operand2 == 0;
}
static class TimerThread implements Runnable {
@Override
public void run() {
for (int i = 0; i >= 0; i--) {
if (Thread.interrupted()) {
return;
}
System.out.println("剩余时间: " + i + "秒");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
if (!Thread.interrupted()) {
System.out.println("时间到!");
}
}
}
}
//在倒计时的时候顺序有点错误