【发布时间】:2015-06-08 02:50:26
【问题描述】:
这是为了上课。我无法弄清楚如何最好地将用户输入与数组答案键进行比较,从而对给出的答案进行评分。我试着搜索了一段时间,但找不到我需要的东西,所以任何指针都将不胜感激!
练习的提示是:
编写一个 DMV 程序,对驾照考试的笔试部分进行评分。它应该有20个多项选择题。它应该要求用户为 20 个问题中的每一个问题输入学生的答案,这些问题应该存储在另一个数组中。输入学生的答案后,程序应显示一条消息,指示学生通过或未通过考试。(学生必须正确回答 20 个问题中的 15 个才能通过考试)。然后它应该显示正确回答的问题总数和错误回答问题的总数。输入验证:只接受字母 A、B、C 或 D。
到目前为止我的代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] answerkey = {"b","d","a","a","c","a","a","d","b","b","b","d","c","a","c","c","a","d","a","a"};
int n = 0;
int correct = 0;
int incorrect = 0;
String answer = "";
for (int i = 0; i < 20; i++){
System.out.println("Please enter your answers. Acceptable input is limited to A,B,C and D.\n");
answer = input.next();
if (answer.compareTo(answerkey[0])==0){
correct++;}
else {incorrect++;}
}
if (correct > 14){
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
System.out.println("You have " + correct + " correct answers.");
System.out.println("You have " + incorrect + " incorrect answers.");
}
【问题讨论】:
-
@HovercraftFullOfEels 不,实际上......我的具体问题(如帖子开头所述)是我不知道如何将给定的用户输入与正确答案数组进行比较。例如,如果答案是 [1,2,3,4,5] 并且用户输入是 [1,2,3,8,5] 它应该报告一个元素不同。我需要知道的是有什么方法可以做到这一点?
-
在你的 for 循环中,如果布尔检查,你将在答案数组中检查的数组项硬编码为仅第 0 项而不是对应于第 i 个问题的答案项:@987654322 @。不应该是
if (answer.compareTo(answerkey[i]) == 0) {还是if (answer.equals(answerkey[i])) {? -
啊。不知道我是怎么错过的,非常感谢。
-
我完全错过了你的问题——很抱歉。
标签: java arrays if-statement