英文:
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 < 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;
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论