astrae
astrae

Reputation: 63

Why is my Java code not working (beginner, array)

thanks for looking. I'm stuck on why this is not handling cases for inputted grades. It handles A+ fine (returns 4.0) but 'A' gives an error, 'A-' gives 4.0 (should be 3.7), then 'B+' is correct, 'B' gives error, 'B-' gives 3.0 (should be 2.7), and this is the pattern. Any thoughts?

public class Grade {
    private String grade = "";
    public Grade(String grade) {
        this.grade = grade;
    public double getgrade() {
        double gpa = 0.0;
        char[] gradeArray = this.grade.toCharArray();
        if (gradeArray[0] == 'A') {
            gpa += 4.0;
        }
        if (gradeArray[0] == 'B') {
            gpa += 3.0;
        }
        if (gradeArray[0] == 'C') {
            gpa += 2.0;
        }
        if (gradeArray[0] == 'D') {
            gpa += 1.0;
        }        
        if (gradeArray[1] == '+') {
            if (gradeArray[0] != 'A') {
                gpa += 0.3;
            }
        }
        if (gradeArray[0] == '-') {
            gpa -= 0.3;
        }
        return gpa;
    }
}```

Upvotes: 0

Views: 84

Answers (2)

pulkit16
pulkit16

Reputation: 1

public class Grade {

private String grade = "";

public Grade(String grade) {
    this.grade = grade;
}

public String getLetterGrade() {
    return this.grade;
}

public double getNumericGrade() {
    double gpa = 0.0;
    char[] gradeArray = this.grade.toCharArray();

    // Good to have null/empty check always
    if ( gradeArray.length == 0  || gradeArray[0] == ' '){
        return 0;
    }

    // Code readability increases manifolds with switch. if clause can also be used
    // Considering only the cases you originally had. With this your code block at last becomes redundant
    switch ( gradeArray[0] ){
        case 'A': gpa += 4.0; break;
        case 'B': gpa += 3.0; break;
        case 'C': gpa += 2.0; break;
        case 'D': gpa += 1.0; break;
        default: break;
    }

    // First you need to check if there is a second character present or not
    // If present then it should be only +/-
    if( gradeArray.length == 2 && ( gradeArray[1] == '+' || gradeArray[1] == '-' )){
        if (gradeArray[1] == '+') {
            if (gradeArray[0] != 'A') {
                gpa += 0.3;
            }
        }
        // '-' would be second character, so index should be 1
        if (gradeArray[1] == '-') {
            gpa -= 0.3;
        }
    } //Include else to handle other scenarios

    return gpa;
}

}

Upvotes: 0

Michal Drozd
Michal Drozd

Reputation: 1351

well if you call A or B, e.g.:

new Grade("A").getNumericGrade()

you get java.lang.IndexOutOfBoundsException on line

if (gradeArray[1] == '+') {

because gradeArray[1] does not exist, there is only 1 character (at index 0) it is 'A' or 'B'

Simple solution: check for length! E.g.:

if (gradeArray.length > 1 && gradeArray[1] == '+') {

Upvotes: 1

Related Questions