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

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

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

问题

  1. 当我尝试以这种方式返回时,编译器会抛出一个错误。
  2. > 编译错误信息 Main.java:15: 错误: 缺少return语句
  3. > }
  4. > ^ 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);

  1. if(distanceB > distanceA) {
  2. return "距离 A";
  3. }
  4. else if(distanceB < distanceA) {
  5. return "距离 B";
  6. }
  7. else if(distanceB == distanceA) {
  8. return "距离 C";
  9. }
  10. }

}

  1. *剩余代码。*
英文:

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

  1. public class Main {
  2. static String distances(int x, int y, int z) {
  3. int distanceA = Math.abs(z-x);
  4. int distanceB = Math.abs(z-y);
  5. if(distanceB > distanceA) {
  6. return "distance A";
  7. }
  8. else if(distanceB < distanceA) {
  9. return "distance B";
  10. }
  11. else if(distanceB == distanceA) {
  12. return "distance C";
  13. }
  14. }
  15. }

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:

确定