如何获得二维数组中每列的相等匹配数?

时间:2018-03-06 13:07:50

标签: java

我有一个名为correctAnswer的数组,它有10个值。每个值都是A,B,C或D.

然后我有一个名为studentAnswers的二维数组,它有3行10列。 我想创建一个方法来检查每列的匹配数。

例如:

正确答案:[B,C,A,A,B,A,C,D,A,C]

学生1结果:C,D,C,D,B,D,C,C,A,B 学生2结果:A,A,B,C,D,C,B,B,D,D 学生3结果:A,C,C,C,B,C,A,A,A,A

然后它应该打印:

答案1:0 答案2:1 等等......直到它达到10,因为数组中有10个值为correctAnswers

到目前为止,这是我的代码:

private char[] correctAnswer = { 'B', 'C', 'A', 'A', 'B', 'A', 'C', 'D', 'A', 'C' };

private char[][] studentAnswers;

// constructor
    public MultipleChoice(int numberOfStudents) {
    studentAnswers = new char[numberOfStudents][10];
    for (int i = 0; i < studentAnswers.length; i++) {
        for (int j = 0; j < studentAnswers[i].length; j++) {
            int tal = (int) (Math.random() * 4);
            char c = (char) (tal + 'A');
            studentAnswers[i][j] = c;
        }
    }
}

// my method
public void printCorrectAnswerPrQuestion() {
    for (int i = 0; i < correctAnswer.length; i++) {

        System.out.print("number of correct answers to question number " + correctAnswer[i + 1] + ": ");
        int correctAnswers= 0;

        for (int j = 0; j < correctAnswer.length; j++) {
            if (correctAnswer[j] == studentAnswers[i][j]) {
                correctAnswers= correctAnswers+ 1;
            }
        }
        System.out.print(correctAnswers);
        System.out.println();
    }
}

1 个答案:

答案 0 :(得分:1)

外部for循环i < correctAnswer.length上的条件错误。它必须是studentAnswers.length。这将为每个学生提供正确答案的数量。

如果您想知道正确回答问题的学生人数

for (int i = 0; i < correctAnswer.length; i++) {
    int correctAnswers = 0;
    System.out.print("number of correct answers to question number " + i + ": ");

    for (int j = 0; j < studentAnswers.length; j++) {
        if (correctAnswer[i] == studentAnswers[j][i]) {
            correctAnswers = correctAnswers + 1;
        }
    }
    System.out.println(correctAnswers);
}