如何从我的阵列中找到前三个测试分数+名称

时间:2016-02-17 06:39:32

标签: java arrays loops if-statement for-loop

我完成了我的任务的前两个步骤,关于我的老师想要我的方式,其中包括: 计算并打印每个考试的平均分数 计算并打印每位学生和得分最高的学生的平均分数

现在我无法弄清楚如何获得它所以它显示了前三名得分学生及其分数

我想这样做,而不是按升序/降序对数组进行排序

到目前为止我的代码是:

public class GradeBook {
public static void main(String[] args) {

    String[] names = {"Alex", "Barry","Cindy", "Deb", "Eric", "Fran", "Gary", "Helen"};

    int[][] grades = {
            { 77, 83, 96 },
            { 88, 67, 78 },
            { 92, 77, 76 },
            { 94, 42, 81 },
            { 99, 54, 72 },
            { 90, 46, 54 },
            { 76, 59, 88 },
            { 94, 69, 88 }
    };

    int rSize = grades[0].length;
    int cSize = grades.length;
    double avg = 0;
    double maxNum = 0;
    double avgSc = 0;
    ArrayList<Double> avgScores = new ArrayList();
    ArrayList topThree = new ArrayList();

    // calculate and print the average score for each exam
    for (int r = 0; r < rSize; r++) {
        avg = 0;

        for (int c = 0; c < cSize; c++) {
            avg += grades[c][r];
        }

        avg /= cSize;
        DecimalFormat a = new DecimalFormat("#.##");
        double x = Double.parseDouble(a.format(avg));

        System.out.println("\nThe average grade for Exam #" + (r+1) + ": " +x);
    }


    // calculate and print the average score for each student, and the top scoring student
    for (int c = 0; c < cSize; c++) {
        avgSc = 0;

        for (int r = 0; r < rSize; r++) {
            avgSc += grades[c][r];

        }

        avgSc /= rSize;
        DecimalFormat a = new DecimalFormat("#.##");
        double x = Double.parseDouble(a.format(avgSc));

        System.out.println("\nThe average grade for " + names[c] + ": " +x);
        avgScores.add(avgSc);

    }

    maxNum = 0;
    int topI = -1;
    for (int i = 0; i<cSize; i++) {

        if (avgScores.get(i) > maxNum){
            maxNum = avgScores.get(i);
            topI = i;
        }
        else {
            continue;
        }
    }

    DecimalFormat a = new DecimalFormat("#.##");
    double x = Double.parseDouble(a.format(maxNum));
    System.out.println("\nThe top scoring student is: " + names[topI] + ", who has an average score of: " + x);

    double top1 = 0;
    double top2 = 0;
    double top3 = 0;
    String name1 = "";
    String name2 = "";
    String name3 = "";

    // Some loop that gets the top 3 students and their scores


    }

}

1 个答案:

答案 0 :(得分:0)

我可以想到三种可能的方式:

  1. 排序。参考:http://www.giantbomb.com/forums/off-topic-31/java-enter-number-of-students-enter-grades-and-nam-544969/
  2. 选择算法(找到第k个最大元素)。参考:http://www.careercup.com/question?id=182717
  3. 只需循环分数和相应的学生即可找到前三名学生。