ArrayIndexOutOfBounds
配列にない文字であるキーを提供すると、このメソッドが例外を与える理由を知りたいです。キーが文字以外の場合、値を返すことに問題はないようです。
public class BinarySearch2 {
public static void main(String[] args) {
String[] array = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
String key = "K";
String found = binarySearch(array, key);
System.out.println(found);
}
public static String binarySearch(String[] array, String key) {
int low = 0;
int high = array.length;
int mid = (low + high)/2;
//int i = 0;
while (low <= high) {
//System.out.print(i + " ");
if (array[mid].compareTo(key) < 0) {
System.out.println(array[mid].compareTo(key));
low = mid + 1;
mid = (low + high)/2;
}
else if (array[mid].compareTo(key) > 0) {
high = mid - 1;
mid = (low + high)/2;
}
else
return array[mid];
//i++;
}
return "-1";
}
}