gpt4 book ai didi

java - 根据数组列表中的对象类型执行不同的行为

转载 作者:行者123 更新时间:2023-12-01 06:11:36 24 4
gpt4 key购买 nike

我正在实现一种考试评分系统。我会尽可能简化信息。每场考试都可以有真题或假题( boolean 值)、填空题(包含所有选项的字符串数组)和多项选择题(也是包含所有选项的字符串数组)。

每个参加考试的学生都有一张答题卡。答案可以是 boolean 值(真或假)或字符串数​​组(用于填空和多项选择题,因为多项选择题也可以有多个答案)。每次学生回答问题时,都会将其添加到答题卡中。

现在评分就是这样进行的。对于真假题,很简单。如果答案正确,奖励积分。但对于填空和多项选择,则有部分学分,例如,如果学生答对了 2/3 的选项,则他获得 2/3 的分数。

我有一个名为 getExamScore(Exam a) 的方法。这是学生评分的地方。我决定创建一个答案键数组列表,其中包含每个问题的所有正确答案。问题编号即索引。示例:

`ArrayList<Object> answerKey = getExamAnswerKey(Exam a);`
System.out.println(answerKey);
//Outputs
[false, false, true, [A, C, D], [int, boolean, double];

我知道拥有对象数组列表通常是不好的做法,但我想不出更好的方法来收集所有答案来比较学生的答案。我对所有学生的答案都有一个类似的 arrayList:

ArrayList<Object> studentAnswers = getStudentAnswer(Exam a);
System.out.println(studentAnswers);
//Outputs
[False, true, true, [A, C], [int, boolean]]

现在这就是我被困住的地方。当我在 getExamScore() 方法中对此进行评分时,我想检查 StudentAnswers 的 answerKey 并查看要奖励多少分。但这并不是一个简单的例子 if(studentAnswers[index].equals(answerKey[index])) Score++;

因为字符串数组不能这样比较。所以我想要有一个条件,如果answerKey[index] 和studentAnswers[index] 是一个字符串数组,则有一个for 循环来比较两者并授予适当的分数。如果答案正确,错误,只需比较数值,如果正确,则奖励积分。例如,样本学生的分数如下所示:

[1, 0, 1, 2/3, 2/3] for all the respective problems (partial credit included)

有人可以提出一种实现这种分级设计的方法吗?我也愿意接受对我的数据结构选择的批评。我知道对象的 ArrayList 有一种不好的代码味道,但我真的想不出任何其他方法来收集所有答案。

最佳答案

据我了解,您的问题(您可能应该简化它以使其更清晰)是:

Given an ArrayList<Object>, how can I perform different behavior based on what type of object is in each index of the ArrayList?

答案是您可以使用 instanceof运算符来识别对象的子类型。

for (Object answer : studentAnswers) {
if (answer instanceof String[]) {
// Perform string array grading behavior
} else if (answer instanceof boolean) {
// Perform boolean grading behavior
}
}

关于java - 根据数组列表中的对象类型执行不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33600539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com