这是一堂课。我无法弄清楚如何最好地将用户输入与数组答案密钥进行比较,从而对给出的答案进行评分。我试着寻找一段时间,但却无法找到我需要的东西,所以任何指针都会非常感激!
练习的提示是:
编写一个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.");
}
答案 0 :(得分:0)
在比较用户输入和数组myArray
时尝试此代码。
希望这有帮助。
String[] myArray= { //initialize values here
};
if ((myArray[0]).equals(answer)){
correct++;
} else{
incorrect++;
}
答案 1 :(得分:-1)
使用动态索引访问变量。现在,您的每个答案都将与第一个答案进行比较(&#34; b&#34;)
这方面的一个例子是
String[] myArray = { //initialize values here
};
for (int index = 0; index <= myArray.length-1; index++){
if (answer.equals(myArray[index]){
correct++;}
else{
incorrect++;}
}