Java中如何统计字符串数组匹配数并生成考试评分结果?
模拟考试程序评分功能优化方案
我正在开发一个可评分的模拟考试程序,主模块获取用户输入的20道选择题答案(A、B、C、D),通过for循环填充
answerKeyArray(答案键数组)和testAnswers(用户答案数组)。目前已通过equals语句逐个对比两个数组,判断每题对错并输出每题结果,但希望改为统计正确、错误答案的数量,计算得分并输出类似「您以90%的成绩通过考试,恭喜!」「正确答案数量:18,错误答案数量:2」的结果。
现有代码片段:
int arraySize; arraySize = 20; // Declare and assign the variables to create the parallel array int count; // Access the contents of both arrays for (count = 0; count <= arraySize - 1; count++) { System.out.println(); // Message to display the Answerkey and testAnswer System.out.println("The correct answer to question " + (count + 1) + " is: " + answerKeyArray[count]); System.out.println("Your answer to question " + (count + 1) + " is: " + testAnswers[count]); // Find the correct and incorrect answers if (answerKeyArray[count].equals(testAnswers[count])) { // Message to display the answer is correct System.out.println("Question " + (count + 1) + " is correct "); } else { // Message to display the answer is incorrect System.out.println("Question " + (count + 1) + " is incorrect "); } }
修改实现方案
- 添加统计变量:在循环外部声明两个计数器,分别记录正确、错误答案的数量
- 更新循环逻辑:在对错判断的分支中,对应递增计数器
- 计算得分并输出结果:循环结束后计算得分百分比,按需求格式打印最终统计信息
修改后的完整代码:
int arraySize = 20; int count; // 初始化统计计数器 int correctCount = 0; int incorrectCount = 0; // 遍历对比答案并统计 for (count = 0; count < arraySize; count++) { System.out.println(); System.out.println("The correct answer to question " + (count + 1) + " is: " + answerKeyArray[count]); System.out.println("Your answer to question " + (count + 1) + " is: " + testAnswers[count]); if (answerKeyArray[count].equals(testAnswers[count])) { System.out.println("Question " + (count + 1) + " is correct "); correctCount++; } else { System.out.println("Question " + (count + 1) + " is incorrect "); incorrectCount++; } } // 计算得分百分比(强制转double避免整数除法精度丢失) double scorePercentage = (double) correctCount / arraySize * 100; // 打印最终结果 System.out.println("\n===== 考试结果 ====="); System.out.println("正确答案数量:" + correctCount + ",错误答案数量:" + incorrectCount); if (scorePercentage >= 60) { // 可根据需求调整及格分数线 System.out.printf("您以%.1f%%的成绩通过考试,恭喜!\n", scorePercentage); } else { System.out.printf("您的成绩为%.1f%%,未通过考试,请继续努力!\n", scorePercentage); }
细节说明
- 将
count <= arraySize - 1简化为count < arraySize,符合Java数组遍历的常规写法 - 使用
printf格式化输出百分比,保证显示更美观 - 及格分数线可根据实际需求修改阈值
内容的提问来源于stack exchange,提问作者TeeJ10
相关产品推荐
相关产品推荐

