java - Incorrect GPA method computation -
this question has answer here:
- how compare strings in java? 23 answers
my method keeps returning 0
. can me find why gpa not compute?
public static double getgpa(string a) { double value = 0; double sum = 0; for(int = 0; i<a.length(); i++) { string grade = a.substring(i,i+1); if(grade == "a") value = 4; if(grade == "b") value = 3; if(grade == "c") value = 2; if(grade == "d") value = 1; if(grade == "f") value = 0; sum += value; } return sum/(a.length()+1); }
you should using .equals(), not ==.
you've got couple of lesser mistakes:
- you're dividing string length plus one.
- you're not handling invalid inputs sensibly. error or ignore.
here's corrected copy:
public static double getgpa(string a) { long total = 0; long count = 0; for(int = 0; i<a.length(); i++) { string grade = a.substring(i,i+1); count++; if(grade.equals("a")) total += 4; else if(grade.equals("b")) total += 3; else if(grade.equals("c")) total += 2; else if(grade.equals("d")) total += 1; else if(grade.equals("f")) total += 0; else count--; /* ignore invalid characters, e.g. whitespace. */ } return total / (double) count; }
Comments
Post a Comment