动手动脑

import java.util.*;

public class FourArithmeticTest {
static List questionList = new ArrayList<>(); //保存已经生成的题目,去重
static int errorCount = 0;
static final int TOTAL = 30;

// 主方法,启动考试
public static void main(String[] args) {
startExam(120); //设置总考试时间120秒,可以修改
}

//1. 生成随机数字 0~99
public static int getRandomNum(){
Random r = new Random();
return r.nextInt(100)+1;
}

//2. 随机获取运算符 + - * /
public static char getOp(){
char[] ops = {'+','-','*','/'};
Random r = new Random();
return ops[r.nextInt(4)];
}

//3. 生成一道符合所有约束的题目,返回数组 [题目,答案]
public static String[] createOneQuestion(){
while(true){
int a = getRandomNum();
int b = getRandomNum();
char op = getOp();
int ans = 0;
boolean ok = true;
switch(op){
case '+':
ans = a+b;
break;
case '-':
if(a < b) ok = false; //减法不能负数
ans = a-b;
break;
case '':
ans = a
b;
if(ans >=1000) ok = false; //乘法不能四位数
break;
case '/':
if(b==0 || a % b !=0) ok = false; //除法必须整除
ans = a / b;
break;
}
String q = a + op + b;
if(ok && !isRepeat(q)){
questionList.add(q);
return new String[]{q+"= ?",String.valueOf(ans)};
}
}
}

//4. 判断题目是否重复
public static boolean isRepeat(String q){
return questionList.contains(q);
}

//5. 启动考试,带倒计时(单位秒)
public static void startExam(int totalTime){
Scanner sc = new Scanner(System.in);
long startTime = System.currentTimeMillis();
for(int i=1;i<=TOTAL;i++){
long now = System.currentTimeMillis();
long used = (now - startTime)/1000;
if(used >= totalTime){
System.out.println("考试超时!剩余题目全部判错");
errorCount += (TOTAL - i + 1);
break;
}
String[] qna = createOneQuestion();
System.out.print("第"+i+"题:"+ qna[0] + " 你的答案:");
String userInput = sc.nextLine();
if(userInput.equals(qna[1])){
System.out.println("正确");
}else{
System.out.println("错误,正确答案:"+qna[1]);
errorCount++;
}
}
calcResult();
}

//6. 统计结果
public static void calcResult(){
System.out.println("\n考试结束,成绩统计");
System.out.println("总题目数:"+TOTAL);
System.out.println("错题数量:"+errorCount);
double rate = (TOTAL - errorCount)*100.0 / TOTAL;
System.out.printf("正确率:%.2f %%",rate);
}
}
1. Java方法重载:同名方法,不同参数列表,实现同一个功能适配不同类型输入
​
2. 模块化编程思想:把一个大程序拆分成多个独立方法,方便维护,也是本次四则运算实验的核心要求
​
3. 随机数、集合去重、时间戳实现倒计时,完成小学自动出题系统,满足全部约束条件。

posted @ 2026-10-08 21:32  杨臣心  阅读(9)  评论(0)    收藏  举报