因此,当我遇到 this 时,我一直在 CodingBat 网站上练习我的 Java 编程技能。问题。在其中,您必须制作一个简单的方法,该方法接受动态长度的整数数组,检查数组中的元素是否按递增顺序(1、2、3、15678 等),然后返回“true "如果为 true,如果整数顺序错误则为 "false"。
首先,我初始化了一个名为“result”的 boolean 变量。然后,我遍历该方法传递的整数数组。如果当前索引值小于下一个索引值,我将“result”设置为“true”,并重复循环。否则,我会将“result”设置为“false”,跳出循环并将“result”设置为“false”。在 FOR 循环之后,我返回“结果”。
但是,我一直收到“result”未正确初始化的错误消息。我有点理解与 JVM 的混淆,但我认为在 IF/ELSE 语句中设置“结果”的值可以解决这个问题。
这是我到目前为止完成的代码的副本:
public boolean scoresIncreasing(int[] scores) {
boolean result;
for (int i = 0; i < scores.length; i++) {
if (i < (i + 1)) {
result = true;
}
else {
result = false;
break;
}
}
return result;
}
最佳答案
首先,i < i+1 将始终为真,除非 i = Integer.maxValue,在这种情况下,您将返回到 Integer.minValue。
您想要的是 scores[i] < scores[i+1] ,并且您需要调整循环值以避免在最后一次迭代时索引越界。
因此,您的代码已修复:
public boolean scoresIncreasing(int[] scores) {
boolean result;
for (int i = 0; i < scores.length-1; i++) // fix loop end
{
if (scores[i] < scores[(i + 1)]) {
result = true;
}
else {
result = false;
break;
}
} // missing brace
return result;
}
试试这个作为替代方案。它的工作原理是一旦你弄错了,你可以立即退出。
public boolean scoresIncreasing(int[] scores) {
boolean result = true; // assume true
for (int i = 0; i < scores.length-1; i++) // fix loop end
{
if (scores[i] > scores[(i + 1)]) return false;
} // missing brace
return result;
}
当然,你可能希望在一开始就引入边界检查,以确保至少有两个值。
关于java - 变量未在 for 循环中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3268174/