顺序查询代码怎么不返回-1

来源:百度知道 编辑:UC知道 时间:2024/06/20 09:59:12
public class SequentialSearcher {

public static int search(int[] a, int target) {
int i = 0;
while (i <= a.length && a[i] != target)
i++;

if (i > a.length)
return -1;

else
return i;
}

public static void main(String[] args) {
int[] a = { 45, 87, 93, 64, 51, 76, 78, 83, 99, };
System.out.println(search(a, 75));
}

}

while循环执行到最后,i=9,这时再进行while循环条件判断时,就会出现数组索引越界,所以程序不会再继续执行下去,也就不会输出-1了。

当遇到这种问题的时候,建议进行debug,跟踪关键变量的值,这样就会发现一些由于思维定势而想不到的问题。

i不大于a

public class SequentialSearcher {
public static int search(int[] a, int target) {
int i = 0;
while (i < a.length && a[i] != target) {
i++;
}
if (i == a.length) {
return -1;
} else {
return i;
}
}

public static void main(String[] args) {
int[] a = { 45, 87, 93, 64, 51, 76, 78, 83, 99, };
System.out.println(search(a, 75));
}
}

你的数组是啊a[0]~a[8] , a.length=9.所以i的循环应该是0~8,所以你的程序为出现索引越界。
如果修改成
public class SequentialSearcher {
public static int search(int[] a, int target) {
int i = 0;
while (i <= a.length-1 && a[i] != target)
i++;

if (i+1 > a.length)
return -1;

else
return i;
}

public static void main(String