获取二维数组的用户字符输入



我需要找到一种方法将用户的 t/f 答案放入数组中,以便可以根据键检查它们。我现在得到了一个永无止境的循环。我不确定我该如何避免这种情况。

public class TrueFalse {
    public static void main(String[] args) {
        DecimalFormat mine = new DecimalFormat("##0.0");
        Scanner input = new Scanner(System.in);
        //Creates an array to store student answers
        char [][] studentAnswers = new char[8][11];
        System.out.println(" please enter T/F");
        for (int h = 0; h < studentAnswers[h].length; h++){
            for (int k = 0; k < studentAnswers.length; k++){
                studentAnswers[k][h] = input.next().charAt(0);
            }
        }
        //Answer Key that will be compared to student answers
        char [] keys = {'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'F', 'F'};

        //Grading the user answers
        for (int i = 0; i < studentAnswers.length; i++){
            //Grade for one student
            int score = 0;
            for (int j = 0; j < studentAnswers[i].length; j++){
                if(studentAnswers[i][j] == keys[j])
                ++score;
            }
            double average = (double)score / studentAnswers.length  * 100; 
            System.out.println("Student number " + i + " score was: " + mine.format(average));
        }
    }
}

您可以尝试使用以下代码打印平均值:

for (int i=0; i < studentAnswers[i].length; ++i) {
    int score = 0;
    for (int j=0; j < studentAnswers.length; ++j) {
        if (studentAnswers[j][i] == keys[j]) {
            ++score;
        }
    }
    DecimalFormat df = new DecimalFormat(".##");
    double average = (double)score / studentAnswers.length;
    System.out.println("Student number " + i + " score was: " + df.format(average));
}

最新更新