计算学生的GPA

时间:2018-12-22 01:48:53

标签: java arrays

创建一个Java程序,该程序将读取属于一个名为John的学生的字母等级的数组,如下所示:

char John [] = {'A','B','A','C','F','B','A','D','A','C'};

每个年级的分数如下:

A = 4,B = 3,C = 2,D = 1,F = 0

您的程序是读取数组中的每个元素,验证字母等级(必须为A,B,C,D或F),将等级与适当的等级点相匹配,并显示平均绩点(GPA)为约翰。您的程序将在到达数组的最后一个索引时停止处理。

这是我尝试过的但无法获得正确的GPA。

public static void main(String [] args)
{

    int gradepoint;
    char grade = ' ';
    double sum = 0;

    char John [] = {'A','B','A','C','F','B','A','D','A','C'};

    for (char c : John) {
    switch(c)
    {
    case 'A' : gradepoint = 4; break;
    case 'B' : gradepoint = 3; break;
    case 'C' : gradepoint = 2; break;
    case 'D' : gradepoint = 1; break;
    case 'F' : gradepoint = 0; break;
    }
    }

    for (int counter = 0; counter < John.length; counter++) {
        sum += John[counter];
    }
    double gpa = sum/10;

    System.out.println("GPA : " + gpa );
}

}

3 个答案:

答案 0 :(得分:2)

对于遍历数组的每次迭代,将字母的值添加到总和,然后将总和除以数组的大小。

for (char c : John) {

            switch(c)
            {
                case 'A' : gradepoint = 4; break;
                case 'B' : gradepoint = 3; break;
                case 'C' : gradepoint = 2; break;
                case 'D' : gradepoint = 1; break;
                case 'F' : gradepoint = 0; break;
            }

            sum += gradepoint;
}

double gpa = sum/John.length;
System.out.println("GPA : " + gpa ); // GPA: 2.7

答案 1 :(得分:1)

sum += John[counter];正在向您的sum添加字母(您需要在循环中执行switch)。您还忘记了检查成绩是否有效。您想要类似的东西

double sum = 0, count = 0;
char John[] = { 'A', 'B', 'A', 'C', 'F', 'B', 'A', 'D', 'A', 'C' };
for (char c : John) {
    switch (c) {
    case 'A':
        sum += 4;
        count++;
        break;
    case 'B':
        sum += 3;
        count++;
        break;
    case 'C':
        sum += 2;
        count++;
        break;
    case 'D':
        sum += 1;
        count++;
        break;
    case 'F':
        count++;
        break;
    default:
        System.err.printf("%c is not a valid grade.%n", c);
    }
}
double gpa = sum / count;

System.out.println("GPA : " + gpa);

答案 2 :(得分:0)

虽然已经发布了答案,但我想给您一些建议。

在这种情况下,就性能和简单性而言,与Mapif相比,使用switch是更好的选择。

这是我使用Map and Stream的代码:

Character John [] = {'A','B','A','C','F','B','A','D','A','C'};
Map<Character, Integer> gradeValues = new HashMap<>();

gradeValues.put('A', 4);
gradeValues.put('B', 3);
gradeValues.put('C', 2);
gradeValues.put('D', 1);
gradeValues.put('F', 0);

OptionalDouble val = Arrays.asList(John).stream()
                        .map(c -> gradeValues.get(c)).mapToInt(g -> (int) g)
                        .average();

System.out.println("GPA: " + val.getAsDouble());