数字代码的Java标志

时间:2013-10-13 01:13:48

标签: java

我试图在这里使用我的代码返回一个数字的符号,但是我使用返回似乎有问题?帮忙吗?

import java.util.*;

public class ReturnTest {
    public static int sign(int n) {
        if (n > 0)
            return 1;
        else if (n == 0)
            return 0;
            else if (n < 0)
                return -1;
    }

3 个答案:

答案 0 :(得分:3)

问题是您没有从方法中的所有路径返回方法。您可以根据Oracle Java Code Conventions

相应地缩进代码来查看此内容
public static int sign(int n) {
    if (n > 0) {
        return 1;
    } else if (n == 0) {
        return 0;
        } else if (n < 0) {
            return -1;
        }
    }
    //needs a return here...
}

这可以通过在底部设置默认返回值来解决。代码可能如下所示:

public static int sign(int n) {
    if (n > 0) {
        return 1;
    } else if (n == 0) {
        return 0;
    }
    return -1;
}

还有其他方法可以实现这一点,但我更愿意根据您当前的实现进行修复。


从您的评论中,看起来您已经迈出了学习Java的第一步。要创建应用程序,您需要一个入口点。这由具有此签名的main方法标记:

public static void main(String[] args)

因此,在您当前的课程中,您可以添加此方法并使用它来调用sign方法。我将展示一个非常基本的样本:

public class ReturnTest {
    public static int sign(int n) {
        if (n > 0) {
            return 1;
        } else if (n == 0) {
            return 0;
        }
        return -1;
    }
    public static void main(String[] args) {
        int n = 10;
        int signOfN = sign(n);
        System.out.println("The sign of " + n + " is: " + signOfN);
    }
}

根据您的需要调整此代码取决于您。我强烈建议你学习基础知识。你可以从这里开始:

答案 1 :(得分:3)

   public static int sign(int n) 
   {
       if (n > 0)
          return 1;
       else if (n < 0)
          return -1;

       return 0;
   }

最后if-else是不必要的。我已经重新订购了“通常”的方式,从零开始。编写这样的代码更短,更清晰,更容易理解

答案 2 :(得分:1)

备用最后一个if(if (n < 0)),因为否则会有一个理论分支,其中函数永远不会离开! 每个分支必须返回!