为什么return语句在if语句内部不起作用?

huangapple go评论63阅读模式
英文:

Why the return statement doesn't work inside if statement?

问题

当我尝试以这种方式返回时,编译器会抛出一个错误。

> 编译错误信息 Main.java:15: 错误: 缺少return语句
>     }
>     ^ 1个错误 退出状态 1

public class Main {
static String distances(int x, int y, int z) {
int distanceA = Math.abs(z-x);
int distanceB = Math.abs(z-y);

    if(distanceB > distanceA) { 
        return "距离 A";
    }
    else if(distanceB < distanceA) {
        return "距离 B";
    }       
    else if(distanceB == distanceA) {
        return "距离 C";
    }
}

}

*剩余代码。*
英文:

When I try to return this way, the compiler throws an error.

> Compile Message Main.java:15: error: missing return statement
> }
> ^ 1 error Exit Status 1

public class Main {
    static String distances(int x, int y, int z) {
        int distanceA = Math.abs(z-x);
        int distanceB = Math.abs(z-y);
        
        if(distanceB > distanceA) { 
            return "distance A";
        }
        else if(distanceB < distanceA) {
            return "distance B";
        }       
        else if(distanceB == distanceA) {
            return "distance C";
        }
    }
}

REST OF THE CODE.

答案1

得分: 0

将最后一个 else if 的部分 'else if(distanceB == distanceA)' 改为 else,然后应该能够正常工作。

英文:

turn the last else if 'else if(distanceB == distanceA)' into else and it should be work

huangapple
  • 本文由 发表于 2020年10月14日 12:09:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64346456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定