【发布时间】:2015-08-11 19:23:13
【问题描述】:
我在 java 中编写了一个方法,该方法将整数数组作为参数,如果该数组包含三个连续的相邻数字,则返回 true。示例 4、5、6 或 23、24、25。我的方法适用于但有一个例外。
问题是我的计数器增加了超过数组索引。索引将大于或等于数组的大小并引发 IndexOutOfBounds 错误。 我的问题是如何增加 i 直到我达到 i
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;
}
}
【问题讨论】:
-
我投票决定将此问题作为离题结束,因为它过于本地化。这曾经是一种选择。