【发布时间】:2015-04-03 15:41:54
【问题描述】:
我在 java 中实现了顺序搜索。但是,我面临数组索引越界异常问题。
当我输入正确的数字时,程序运行正常。但是,当我按下一个不在数组中的数字时,程序会因为“ArrayIndexOutOfBoundsException”而崩溃
public class Sequential {
public static void search (int arr[]) {
Scanner in = new Scanner(System.in);
int key;
int N = arr.length;
int element = 0;
System.out.prinln("Enter the number that you want to search: ");
key = in.nextInt();
while (key != arr[element] && element <= N)
{
element++;
}
if(element > N)
{System.out.println("not found, try again...");}
else
{System.out.println("found, it's in index # " + element);}
}
public static void main (String[]args)
{
int arr[] = { 2, 3, 4, 5, 7, 11, 34, 37, 77 };
search(arr);
}
}
【问题讨论】:
-
向此
(key != arr[element] && element <= N)添加一个条件以防止越界。类似key < N -
@Kon 我同时使用了
element < N和element <= N他们都没有工作。
标签: java arrays algorithm search sequential