gpt4 book ai didi

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 5

转载 作者:行者123 更新时间:2023-12-01 21:43:34 24 4
gpt4 key购买 nike

运行程序后,它引导我到 If (key.compareTo(a[mid]) == 0)它出什么问题了?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at 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);
}
}

最佳答案

不要发送 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);

关于java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36164646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com