gpt4 book ai didi

java - 有人可以解释一下我的 while 循环中的错误吗

转载 作者:行者123 更新时间:2023-12-01 06:44:12 25 4
gpt4 key购买 nike

我一直试图找出为什么代码不断地给我一个 arrayIndexOutOfBoundsException 。出于绝望的尝试,我反转了 while 循环中的 2 个 boolean 条件,并且程序运行良好。这确实让我感到困惑的原因是因为这两个条件由 AND 子句分隔,该子句应该是可交换的。

这是有问题的 while 语句:

while(compareIndex>=0 && key<data[compareIndex])//works
while(key<data[compareIndex] && compareIndex>=0) //Crashes

对于某些上下文,这里是方法主体的其余部分:

public static void insertionSort(int[] data){
for(int i = 0; i<data.length; i++){
int key = data[i];
int compareIndex = i-1;
while(key<data[compareIndex] && compareIndex>=0){
data[compareIndex+1] = data[compareIndex];
compareIndex--;
}
data[compareIndex+1] = key;
}

}

最佳答案

int compareIndex = i-1; // <-- on the first iteration i = 0, and i-1 = -1
while(key<data[compareIndex] && compareIndex>=0)

不能用 -1 索引数组

旁注:您应该在 IDE 中开发代码,并在调试器中单步调试它。如果你不这样做,编程将会变得更加困难。现在就花时间学习如何做到这一点,您将成为一名更好的程序员。试试IntelliJEclipse ,他们是免费的。在谷歌上搜索有关在调试器中单步执行代码的信息。

关于java - 有人可以解释一下我的 while 循环中的错误吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20788491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com