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

时间:2016-02-02 03:15:51

标签: java arrays multidimensional-array

我需要找到一种方法让用户将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));

        }

    }
}

1 个答案:

答案 0 :(得分:0)

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

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));
}