KrissyMichaelsson KrissyMichaelsson - 2 months ago 14
Java Question

What is wrong with my letter to number grade calculator?

I'm trying to make a method with takes a letter grade and returns a numeric grade. It only works tho for letters without pluses or minuses. Here's what I have:

public class Grade{
private String letterGrade;
private double numericGrade;

public Grade(String letterGrade)
{
this.letterGrade = letterGrade;
this.numericGrade = numericGrade;
}

public void getNumericGrade()
{
if (letterGrade.equals("A"))
{
numericGrade = 4.0;
}
else if (letterGrade.equals("B"))
{
numericGrade = 3.0;
}
else if (letterGrade.equals("C"))
{
numericGrade = 2.0;
}
else if (letterGrade.equals("D"))
{
numericGrade = 1.0;
}
else if (letterGrade.equals("F"))
{
numericGrade = 0.0;
}

if (letterGrade.substring(1).equals("+"))
{
numericGrade += .3;
}
else if (letterGrade.substring(1).equals("-"))
{
numericGrade -= .3;
}

System.out.println(numericGrade);

}


It gives 4.0 for "A", but it gives -0.3 for A-. Whats going on here?

Answer

Change your equals to startsWith calls (because "A+" is not equal to "A"), and do the initialization in your constructor (and initializing numericGrade to itself should be giving you a warning). A getter should return the value (not set it). Something like,

private String letterGrade;
private double numericGrade;

public Grade(String letterGrade) {
    this.letterGrade = letterGrade;
    if (letterGrade.startsWith("A")) {
        numericGrade = 4.0;
    } else if (letterGrade.startsWith("B")) {
        numericGrade = 3.0;
    } else if (letterGrade.startsWith("C")) {
        numericGrade = 2.0;
    } else if (letterGrade.startsWith("D")) {
        numericGrade = 1.0;
    } else if (letterGrade.startsWith("F")) {
        numericGrade = 0.0;
    }

    if (letterGrade.substring(1).equals("+")) {
        numericGrade += .3;
    } else if (letterGrade.substring(1).equals("-")) {
        if (numericGrade > 0) {
            numericGrade -= .3; // <-- or an F- is -0.3
        }
    }
}

public double getNumericGrade() {
    // System.out.println(numericGrade);
    return numericGrade;
}