比较学生和正确答案工具、返回错误数量
parent
548d918919
commit
085f016f5b
@ -0,0 +1,68 @@
|
||||
package com.sztzjy.linkCommerce.util;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
//用于比较两个集合的字符串是否对应、返回错误数量和错误位置
|
||||
@Component
|
||||
public class CompareListsUtil {
|
||||
public Result compareLists(String stulist, String answerList) {
|
||||
// 将字符串分割成数组
|
||||
String[] submitted = stulist.split(",");
|
||||
String[] answers = answerList.split(",");
|
||||
|
||||
int errorCount = 0; // 错误数量
|
||||
List<Integer> errorPositions = new ArrayList<>(); // 错误位置
|
||||
|
||||
// 获取较长数组的长度
|
||||
int maxLength = Math.max(submitted.length, answers.length);
|
||||
|
||||
// 遍历较长的数组
|
||||
for (int i = 0; i < maxLength; i++) {
|
||||
String submittedValue = (i < submitted.length) ? submitted[i] : null;
|
||||
String answerValue = (i < answers.length) ? answers[i] : null;
|
||||
|
||||
// 检查对应位置是否相同
|
||||
if (!equals(submittedValue, answerValue)) {
|
||||
errorCount++;
|
||||
errorPositions.add(i + 1); // +1 使位置从 1 开始
|
||||
}
|
||||
}
|
||||
|
||||
return new Result(errorCount, errorPositions);
|
||||
}
|
||||
|
||||
// 自定义 equals 方法处理 null 和空字符串的场景
|
||||
public static boolean equals(String a, String b) {
|
||||
return (a == null ? b == null : a.equals(b));
|
||||
}
|
||||
|
||||
// 内部类用来保存比较结果
|
||||
public class Result {
|
||||
int errorCount;
|
||||
List<Integer> errorPositions;
|
||||
|
||||
Result(int errorCount, List<Integer> errorPositions) {
|
||||
this.errorCount = errorCount;
|
||||
this.errorPositions = errorPositions;
|
||||
}
|
||||
|
||||
public int getErrorCount() {
|
||||
return errorCount;
|
||||
}
|
||||
|
||||
public void setErrorCount(int errorCount) {
|
||||
this.errorCount = errorCount;
|
||||
}
|
||||
|
||||
public List<Integer> getErrorPositions() {
|
||||
return errorPositions;
|
||||
}
|
||||
|
||||
public void setErrorPositions(List<Integer> errorPositions) {
|
||||
this.errorPositions = errorPositions;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue