gpt4 book ai didi

java - 在java while循环中设置计数器的停止点

转载 作者:行者123 更新时间:2023-11-30 03:18:24 25 4
gpt4 key购买 nike

我用java编写了一个方法,它接受一个整数数组作为参数,如果该数组包含三个连续的相邻数字,则返回true。示例 4、5、6 或 23、24、25。我的方法适用,但有一个异常(exception)。

问题是 i 计数器的增加超过了数组索引。索引将大于或等于数组的大小并抛出 IndexOutOfBounds 错误。我的问题是如何增加 i 直到达到 i < array.length 而不是更多。


P.S 我不想在这个方法中使用 For 循环而不是 while 方法!

public class Main {

public static void main(String[] args) {
int[] b = {16, 11, 12, 6, 2, 9, 18, 11};
System.out.println(threeConsecutive(b));

}
public static boolean threeConsecutive(int[] a){
boolean done = false;
boolean result = true;
int n = a.length;
int i = 0;

while (!done && i < n){
if (a[i] + 1 == a[i+1] && a[i] + 2 == a[i+2]) {
done = true;
result = true;
}
else{
done = false;
result = false;
}
i++;

}
return result;
}

}

最佳答案

how to increase i until i reach to i < array.length not more.

i < n已经在这样做了。然而,你真正想要的是 i+2 < n因为你这样做a[i+2] .

简化代码:

for (int i=0; i+2<n; ++i) {
if (a[i]+1 == a[i+1] && a[i]+2 == a[i+2]) {
return true;
}
}

return false;

关于java - 在java while循环中设置计数器的停止点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950247/

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