gpt4 book ai didi

进行二分搜索时出现 java.lang.ArrayIndexOutOfBoundsException 错误?

转载 作者:行者123 更新时间:2023-12-01 19:46:21 27 4
gpt4 key购买 nike

我遇到了一个小问题,我真的不知道为什么。我正在尝试编程以使用二进制搜索方法搜索用户输入的数字。当搜索数组中间的数字时它效果很好,但是当我尝试搜索任何其他数字时会出现错误。这是我的代码。

import java.util.Scanner;

public class Main {

public static void main(String args[])
{
//declaring array
int array[] = {12,23,34,45,56,67,78,89};

//declaring variables
int search = 0;

Scanner input = new Scanner(System.in);

System.out.print("\n Enter: ");
search = input.nextInt();


binarySearch(array, search);
}//end of main

static public void binarySearch(int[] array, int search)
{
int begin = 0;
int end = array.length-1;
int mid = 0;
boolean found = false;

while(!found)
{
mid = (begin + end)/2;

if(array[mid] == search)
{
found = true;
search = array[mid];
}
else if(array[mid] < search)
{
begin = array[mid+1];
}
else if(array[mid] > search)
{
end = array[mid-1];
}

}//end of while loop

//if(!found)
//return ("BOOHOO your search was not found");

System.out.print("Yippee i found "+ search + " at index " + mid);
}

}//end of class

最佳答案

当您找不到搜索时,您需要将 beginend 指针重置为索引,而不是这些索引上的值,即

while(!found)
{
mid = (begin + end)/2;

if(array[mid] == search)
{
found = true;
}
else if(array[mid] < search)
{
begin = mid+1;
}
else if(array[mid] > search)
{
end = mid-1;
}

}//end of while loop

关于进行二分搜索时出现 java.lang.ArrayIndexOutOfBoundsException 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182274/

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