Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 不正确的GPA方法计算_Java_For Loop - Fatal编程技术网

Java 不正确的GPA方法计算

Java 不正确的GPA方法计算,java,for-loop,Java,For Loop,我的方法不断返回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(

我的方法不断返回
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);
}
publicstaticdouble-getGPA(字符串a)
{
双值=0;
双和=0;

对于(inti=0;i您应该使用.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;
    }
    
    publicstaticdouble-getGPA(字符串a)
    {
    长总计=0;
    长计数=0;
    
    对于(int i=0;iSomething缺失,请更正问题。请将问题与完整的代码片段一起发布。您是否使用逐步执行来检查变量的值(尤其是
    grade
    sum
    )代码运行时?不要忘记包含您尝试过的示例输入。不要忘记字符串比较。应在java中使用
    .equals