lundi 21 décembre 2015

Letter grade to number grade using switch/if statements?

I am tasked with creating a java program where the user inputs a grade (D- through A+) and gets a score (0.7 through 4.3)

  • If the user inputs "A", they get 4...."B" = 3...."C" = 2...."D" = 1.

  • If the user inputs a "+" or a "-" after a letter, the final score is incremented or decremented by 0.3

  • So, for example, if the user inputs "C+", they get back a score of "2.3"

So far it works ONLY if the user doesn't add a "+" or "-".

So if the user inputs ONLY a letter, it works.

For some odd reason, if the user inputs a "+" or a "-" after a letter, the output would be "0.3" or "-0.3" respectfully.

I'm not sure why. My AP Comp Sci teacher and I are stumped.

Here is a relevant snip of my code

String letterGrade;
double numericGrade;
Scanner reader = new Scanner(System.in);
public boolean getLetterGrade()
{
    System.out.print("Enter a letter grade: ");
    letterGrade = reader.nextLine();
    return (letterGrade.length() < 3) && (("+".equals(letterGrade.substring(1))) || ("-".equals(letterGrade.substring(1))) || (letterGrade.length() == 1));
}
public double getNumericGrade()
{
    numericGrade = 0.0;
    switch(letterGrade.substring(0).toUpperCase())
    {
        case "A":
            numericGrade += 4.0;
            break;
        case "B":
            numericGrade += 3.0;
            break;
        case "C":
            numericGrade += 2.0;
            break;
        case "D":
            numericGrade += 1.0;
            break;
        case "F":
            numericGrade += 0.0;
            break;
    }
    if ("-".equals(letterGrade.substring(1)))
        numericGrade -= 0.3;
    if ("+".equals(letterGrade.substring(1)))
        numericGrade += 0.3;
    return numericGrade;
}

My guess is that numericGrade is getting reset to 0 after the switch statement, for no reason apparent to me.

Aucun commentaire:

Enregistrer un commentaire