第八天
由两个数的加减乘除推广到四个数
package Randomformation;import java.util.Random;import java.util.Scanner;public class DaTiSystem { public static int c; public static void main(String[] args) { Scanner input = new Scanner(System.in); int totalnum = 5; int completed = 0; long countdownSeconds = 60 * 1000; long endTime = System.currentTimeMillis() + countdownSeconds; Random random = new Random(); System.out.println("答题开始!共有 " + totalnum + " 题,时间限制:60秒"); for (int i = 0; i < totalnum; i++) { // 显示剩余时间 long remainingTime = (endTime - System.currentTimeMillis()) / 1000; if (remainingTime <= 0) { System.out.println("时间到!"); break; } System.out.println("剩余时间:" + remainingTime + "秒"); // 生成题目 System.out.println("第" + (i + 1) + "题:" + generateProblem(random)); try { int number = input.nextInt(); if (number == c) { System.out.println("答案正确"); completed++; } else { System.out.println("答案错误,正确答案是:" + c); } } catch (Exception e) { System.out.println("输入无效,正确答案是:" + c); input.next(); // 清除错误的输入 } } // 修复正确率计算 double correctrate = (double) completed / totalnum * 100; System.out.println("答题结束!答对 " + completed + "/" + totalnum + " 题"); System.out.println("正确率为:" + correctrate + "%"); input.close(); } public static String generateProblem(Random random) { int[] nums = new int[4]; for (int j = 0; j < 4; j++) { nums[j] = random.nextInt(100) + 1; } char[] ops = new char[3]; for (int j = 0; j < 3; j++) { ops[j] = "+-/".charAt(random.nextInt(4)); if (ops[j] == '/') { while (nums[j + 1] == 0 || nums[j] % nums[j + 1] != 0) { nums[j] = random.nextInt(100) + 1; nums[j + 1] = random.nextInt(nums[j]) + 1; } } if (ops[j] == '') { while(nums[j] * nums[j + 1] > 999) { nums[j] = random.nextInt(100) + 1; nums[j + 1] = random.nextInt(nums[j]) + 1; } } if (ops[j] == '-') { while(nums[j] - nums[j + 1] < 0) { int temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } } c = calculateResult(nums, ops); return nums[0] + " " + ops[0] + " " + nums[1] + " " + ops[1] + " " + nums[2] + " " + ops[2] + " " + nums[3] + " = "; } private static int calculateResult(int[] nums, char[] ops) { int[] tempNums = nums.clone(); char[] tempOps = ops.clone(); // 先处理乘除 for (int i = 0; i < tempOps.length; i++) { if (tempOps[i] == '' || tempOps[i] == '/') { int res = tempOps[i] == '' ? tempNums[i] * tempNums[i + 1] : tempNums[i] / tempNums[i + 1]; tempNums[i] = res; // 移动数组元素 for (int j = i + 1; j < tempNums.length - 1; j++) { tempNums[j] = tempNums[j + 1]; } for (int j = i; j < tempOps.length - 1; j++) { tempOps[j] = tempOps[j + 1]; } // 调整数组长度 tempNums = java.util.Arrays.copyOf(tempNums, tempNums.length - 1); tempOps = java.util.Arrays.copyOf(tempOps, tempOps.length - 1); i--; } } // 再处理加减 int result = tempNums[0]; for (int i = 0; i < tempOps.length; i++) { result = tempOps[i] == '+' ? result + tempNums[i + 1] : result - tempNums[i + 1]; } return result; }}
我们也需要考虑加减乘除的优先运算法则