我的方法不断返回0
。有人可以帮我找到为什么GPA无法正确计算吗?
public static double getGPA(String a)
{
double value = 0;
double sum = 0;
for(int i = 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);
}
答案 0 :(得分:0)
你应该使用.equals(),而不是==。
你也有一些较小的错误:
这是一张更正后的副本:
public static double getGPA(String a)
{
long total = 0;
long count = 0;
for(int i = 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;
}