我目前正在从教科书(而不是家庭作业,自学)中进行一项练习,该练习为多选题考试给出了正确答案,我将其命名为answerKey,要求用户输入学生的答案并找到匹配的元素计算成绩。请看我到目前为止所做的。我不明白numCount的行为,为什么它不能正确返回。我想对此提供指导。谢谢!
import java.util.Arrays;
import java.util.Scanner;
public class Drivers_License
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int incorrect = 0;
double grade = 0.0;
String input;
char[] answerKey = {'B', 'D', 'A', 'A', 'C',
'A', 'B', 'A', 'C', 'D',
'B', 'C', 'D', 'A', 'D',
'C', 'C', 'B', 'D', 'A'};
System.out.println();
int numCorrect = 0;
int total = 0;
char[] responses = new char[20];
for (int i = 0; i < responses.length; i++) {
System.out.printf("Enter answer for # %d: ", i+1);
responses[i] = scan.nextLine().toUpperCase().trim().charAt(0);
for (int j = 0; j < answerKey.length; j++) {
if (responses[i] == (answerKey[j])) {
System.out.println(responses[i]);
numCorrect++; // I don't quite understand
// what is happening here...
}
}
}
/* Display elements in userAnswers array */
System.out.println("User answers are below");
for (int i = 0; i < responses.length; i++) {
System.out.print(responses[i] + " ");
}
System.out.println();
}
$ java Drivers_License
Enter answer for # 1: a
Enter answer for # 2: b
Enter answer for # 3: c
Enter answer for # 4: d
Enter answer for # 5: a
Enter answer for # 6: b
Enter answer for # 7: c
Enter answer for # 8: d
Enter answer for # 9: a
Enter answer for # 10: b
Enter answer for # 11: c
Enter answer for # 12: d
Enter answer for # 13: a
Enter answer for # 14: b
Enter answer for # 15: c
Enter answer for # 16: d
Enter answer for # 17: a
Enter answer for # 18: b
Enter answer for # 19: c
Enter answer for # 20: d
No. of correct answers: 100
User answers are below
A B C D A B C D A B C D A B C D A B C D
最佳答案
您正在使用两个for循环(一个在另一个内部)。这些嵌套为循环。
上面的代码中发生的是,对于第一个数组中的每个索引i,第二个数组中的所有j都将被访问。
您要做的是只有一个for循环(共20个迭代),并并行访问两个数组中的元素。
public class Drivers_License
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int incorrect = 0;
double grade = 0.0;
String input;
char[] answerKey = {'B', 'D', 'A', 'A', 'C',
'A', 'B', 'A', 'C', 'D',
'B', 'C', 'D', 'A', 'D',
'C', 'C', 'B', 'D', 'A'};
System.out.println();
int total = 0;
char[] responses = new char[20];
for (int i = 0; i < responses.length; i++)
{
System.out.printf("Enter answer for # %d: ", i+1);
responses[i] = scan.nextLine().toUpperCase().trim().charAt(0);
}
int numCorrect = 0;
for (int i = 0; i < responses.length; i++) {
if (responses[i] == (answerKey[i])) { // Look here
System.out.println(responses[i]);
numCorrect++;
}
}
/* Display elements in userAnswers array */
System.out.println("User answers are below");
for (int i = 0; i < responses.length; i++) {
System.out.print(responses[i] + " ");
}
System.out.println();
}