为什么会报数组越界的错误呢?求大神解答。
错误信息:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -9 out of bounds for length 20
代码: import java.util.Arrays;
import java.util.Scanner;
public class BinarySearch {
public static int rank(int key,int[] a){
int lo = 0, hi = a.length - 1;
while(lo <= hi){
int mid = (lo + hi) / 2;
if(a[mid] > key)
hi = mid - 1;
else if(a[mid] < key)
lo = mid + 1;
else
return mid;
}
return -1;
}
public static void main(String[] args){
int[] a = new int[20];
for(int i = 0; i < 20; i++){
a[i] = (int) (Math.random() * 100);
}
Arrays.sort(a);
for(int cc : a)
System.out.println(cc);
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
int b = 0;
if(in.hasNextInt())
b = in.nextInt();
int address = rank(b,a);
if(address >= 0){
System.out.println("索引为:" + address);
}
else{
System.out.println("目标不存在");
}
}
}