【问题标题】:Counting grades not working计算成绩不起作用
【发布时间】:2016-08-22 09:40:00
【问题描述】:

对于这段代码,我有一个分数分配给一个分数数组。我想计算成绩(例如:A:3 B:4 C:4 ...)。当我运行程序时,它说:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 70
    at ProcessMarks.gradeDistn(ProcessMarks.java:115)
    at ProcessMarks.main(ProcessMarks.java:38)

代码:

char[] grades = new char[testMarks.length];
getGrades(testMarks, grades);
int[] counts = gradeDistn (grades);

for (int i = 0; i < counts.length; i++){
    System.out.println( grades[i] + " : " + counts[i]);

public static void getGrades (int[] testMarks, char[] grades) {
    for (int i = 0; i < testMarks.length; i++) {
        if (testMarks[i] >= 90)
            grades[i] = 'A';
        else if (testMarks[i] >= 75)
            grades[i] = 'B';
        else if (testMarks[i] >= 60)
            grades[i] = 'C';
        else if (testMarks[i] >= 50)
            grades[i] = 'D';
        else if (testMarks[i] >= 45)
            grades[i] = 'E';
        else
            grades[i] = 'F';
    }
}

public static int[] gradeDistn (char[] grades){
    int[] counts = new int[6];
    for (int i = 0; i < grades.length; i++) //count the occurrences
        counts[grades[i]]++;
    return counts;
}

【问题讨论】:

  • 为什么getGrades函数在for循环中?这是您在帖子中输入此内容时的错误吗?

标签: java arrays count


【解决方案1】:

问题出在您的gradeDistn - 函数中。 您尝试使用等级作为数组的索引。但是等级是一个字符,你需要的是一个数字。 Java 只是将您的字符转换为整数,因此转换为字符的 ascii 代码。

所以你可以这样做:

public static int[] gradeDistn (char[] grades){
        int[] counts = new int[6];
        for (int i = 0; i < grades.length; i++) //count the occurrences
            counts[grades[i] - 'A']++;
        return counts;

    }

编辑:

输出应该是这样的:

for(int i = 0; i < counts.length; i++) {
   char gradeAsChar = 'A' + i;
   System.out.println(gradeAsChar + ":"+ counts[i]);
}

【讨论】:

  • 不错!但是还有一个问题,现在只显示F:
  • F:5 F:29 F:38 F:24 F:12 F:17
  • 您能发布生成此输出的代码吗?编辑:哦,对不起。您已经发布了这部分
  • 我认为问题出在 system.print,原因是 (int i = 0; i
  • 它打印所有 Bs 而不是 Fs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 2019-05-11
  • 1970-01-01
  • 2019-08-25
  • 2017-03-01
相关资源
最近更新 更多