运行程序后,它指示我If (key.compareTo(a[mid]) == 0)
它出了什么问题?
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:5 在BinarySearch.search(BinarySearch.java:17)at SearchesDemo.main(SearchesDemo.java:23)
import java.util.Scanner;
import java.util.Arrays;
public class SearchesDemo{
public static void main(String[] args){
BinarySearch searches = new BinarySearch();
int result, key;
Integer [] integerArray = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18};
String [] stringArray = {"apples", "oranges", "peaches", "strawberries", "watermelons"};
System.out.println("Integer test array contains:");
System.out.println(Arrays.toString(integerArray));
for(key = -3; key == 4; key++){
result = searches.<Integer>search(integerArray, 0, 10, key);
searches.toString(Integer.toString(key), result);
}
System.out.println("\nString test array contains:");
System.out.println(Arrays.toString(stringArray)); //toString may not be necessary
result = searches.<String>search(stringArray, 0, 10, "apples");
searches.toString("apples", result);
result = searches.<String>search(stringArray, 0, 10, "plums");
searches.toString("plums", result);
System.out.println("\nProcess completed.");
}
}
public class BinarySearch{
public static <T extends Comparable> int search(T [] a, int first, int last, T key){
int result = 0; //to keep the compiler happy.
if (first > last)
result = -1;
else{
int mid = (first + last)/2;
if (key.compareTo(a[mid]) == 0)
result = mid;
else if (key.compareTo(a[mid]) < 0)
result = search(a, first, mid - 1, key);
else if (key.compareTo(a[mid]) > 0)
result = search(a, mid + 1, last, key);
else{
System.out.println("Error");
result = -1;
}
}
return result;
}
public static void toString(String key, int result){
if(result == -1)
System.out.println(key + " is not in the array.");
else
System.out.println(key + " is at index " + result);
}
}
答案 0 :(得分:1)
请勿为10
值发送last
。只需发送数组的长度。
result = searches.<String>search(stringArray, 0, stringArray.length, "apples");
searches.toString("apples", result);
result = searches.<String>search(stringArray, 0, stringArray.length, "plums");
searches.toString("plums", result);
同样在这里:
result = searches.<Integer>search(integerArray, 0, integerArray.length, key);
答案 1 :(得分:1)
问题是你的stringArray中有5个元素(索引0,1,2,3,4),并且因为你从开始索引为0开始,最后是10,因此介质是5,因此你试图访问不存在的索引 - &gt;出界。
答案 2 :(得分:1)
主方法中的行号 23 发生异常。您将开始和结束索引传递为0和10。
result = searches.<String>search(stringArray, 0, 10, "apples");
stringarray
的长度仅为5.当计算中间值时,它变为(0+10)/2
,即5. arr[5]
抛出arrayIndexOutOfBound
例外。