如何在方法中初始化结果?

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

how to initialize result in method?

问题

result没有初始化,如何在这个方法中初始化它?(以保留代码的功能性)

static int maxNumbers(int r, int s) {

    int result = 0; // 初始化result
    int[] rk = new int[r];

    for (int i = 0; i < rk.length; i++) {
        if (s > 1) {
            rk[i] = (s - 1) + 1;
            s--;
        } else if (s == 1) {
            rk[i] = (s + 1) + 1;
            s = 0;
        } else {
            rk[i] = 1;
        }
    }
    for (int i = 0; i < rk.length; i++) {
        result = rk[0] * 2 * rk[i] * 2;
    }

    return result;
}
英文:

result isn't initialized, how to do it in this method?(to preserve the functionality of the code)

static int maxNumbers(int r, int s) {

    int result;
    int[] rk = new int[r];

    for (int i = 0; i &lt; rk.length; i++) {
        if (s &gt; 1) {
            rk[i] = (s - 1) + 1;
            s--;
        } else if (s == 1) {
            rk[i] = (s + 1) + 1;
            s = 0;
        } else {
            rk[i] = 1;
        }
    }
    for (int i = 0; i &lt; rk.length; i++) {
        result = rk[0] * 2 * rk[i++]*2;
    }


    return result;
}

答案1

得分: 2

关于整数原始类型和您的示例,您可以简单地写成 int result = -1;

虽然您在第二个 for 循环中设置了 result 变量,但编译器无法保证该 for 循环实际循环,因此该变量可能不会被设置。

因此,在最后,您应该检查方法的结果。

英文:

For the integer primitive and regarding your example you can simply write int result = -1;.

Although you set your result variable in the 2nd for loop, the compiler cannot guarantee that this for loop actually loops and therefore the variable will be set.

So in the end you should check the result of the method.

huangapple
  • 本文由 发表于 2020年8月6日 03:26:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63272260.html
匿名

发表评论

匿名网友

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

确定