一个java程序运行时出错

来源:百度知道 编辑:UC知道 时间:2024/05/31 15:32:31
package P1;

public class Search
{
//顺序查找
public static int sequentialSearch(int arr[],int key)
{
for(int k=0;k<arr.length;k++)
if(arr[k]==key)
return k; //成功,返回该数组元素的位置(即索引)
return -1;//失败,返回-1
}

//折半查找
public static int binarySearch(int arr[],int key)
{
int low=0; //初始化
int high=arr.length-1;
while(low<=high)
{
int mid=(low+high)/2; //取折半值
if(arr[mid]==key)
return mid; //成功,返回该数组元素的位置(即索引)
else if(arr[mid]<key)
low=mid+1; //定位查找上半段
else
high=mid-1; //定位查找下半段
}
return -1; //失败,返回-1
}
public static void main(String args[])
{
int i=1;
int ArrayList[]=new int[1000];
for(i=1;i<=1000;i++)
{
ArrayList[i]=i;
}
System.out.println(sequentialSearch(ArrayList,500));//顺序查找
System.out.println(binarySearch(ArrayL

此问题是因为数组越界引起的
此句定义 int ArrayList[]=new int[1000];
所以 ArrayList[]长度是0-999
所以 i要小于1000而不能等于1000,否则会引发java.lang.ArrayIndexOutOfBoundsException异常

for(i=1;i<=1000;i++)
i要小于1000,否则出界。