计算gpa是返回错误

时间:2017-10-30 21:43:33

标签: java

Hy先生,我需要快速帮助我的支持。我试着调试这个代码,我不知道我怎么会得到这个错误但是当我尝试计算gpa时它发送的是0而不是来自switch的值。 如果用户按A和4,则需要返回4 * 4但是对于字母A我正在接收0

public class Gpa{
    private int sumOfCredits;
    private int sumOfPoints;
    private int points = 0;

    public Gpa(){
        sumOfPoints=0;
        sumOfCredits=0;
    }

    public static int calcPoints(String grade) {
        int points = 0;
        switch (grade) {
            case "A":
                points = 4;
                break;
            case "B":
                points = 3;
                break;
            case "C":
                points = 2;
                break;
            case "D":
                points = 1;
                break;
            case "F":
                points = 0;
                break;
            case "a":
                points = 4;
                break;
            case "b":
                points = 3;
                break;
            case "c":
                points = 2;
                break;
            case "d":
                points = 1;
                break;
            case "f":
                points = 0;
                break;
            default:
                points = -1;
        }
        return points;
    }

    public int getSumOfCredits(){
        return sumOfCredits;
    }

    public int getSumOfPoints(){
        return sumOfPoints;
    }

    public void addToTotals(String grade,int credits){
        sumOfCredits =+  credits;
        calcPoints(grade);
     sumOfPoints =sumOfPoints + points * credits;
    }

    public double calcGPA(){
        double gpa = sumOfPoints /sumOfCredits;
        return gpa;
    }
}

这是我的测试人员课程:

import java.util.*;

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

        Scanner scan = new Scanner(System.in);
        Gpa gpaC = new Gpa();

        for (int i = 1; i <= 3; i++) {
            System.out.printf("Enter grade (one character): ");
            String grade = scan.next();
            System.out.printf("Enter credits: ");
            int credits = scan.nextInt();
            gpaC.addToTotals(grade, credits);
            System.out.printf("Sum Points: %d", gpaC.getSumOfPoints());
            System.out.printf("\tSum Credits: %d\n", gpaC.getSumOfCredits());
        }
        System.out.printf("GPA: %.2f", gpaC.calcGPA());
    }
}

2 个答案:

答案 0 :(得分:0)

 double gpa = sumOfPoints /sumOfCredits;

是java中的整数除法,它将返回一个整数值。有可能它始终是0到1之间的值,在被转换为整数后将等于0。看看是否将它们转换为双重修复它。

double gpa = (double)sumOfPoints / (double)sumOfCredits;

您还在此处重新定义每个循环上的点数:

    public static int calcPoints(String grade) {
    int points = 0;
    switch (grade) {

这意味着您不是更改全局变量points而是更改局部变量points。所以你需要删除那个局部变量点,所以它使用全局变量点,你也不需要返回任何东西,所以只需使用void:

public void calcPoints(String grade) {
     switch (grade) {
       //cont

答案 1 :(得分:0)

在你的calcGPA()方法中,当你想进行浮动除法时,你正在进行整数除法。您必须将sumOfPoints变量或sumOfCredits转换为double。