顺序搜索数组在java中超出了绑定问题

时间:2015-04-03 15:41:55

标签: java arrays algorithm search sequential

我在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);
}
}

2 个答案:

答案 0 :(得分:0)

您的代码几乎没有问题,请查看我修改后的代码。应该帮助你。

public static void search (int arr[]) {
    Scanner in = new Scanner(System.in);
    int key;
    int N = arr.length;
    int element = 0;

    System.out.println("Enter the number that you want to search: ");
    key = in.nextInt();
    boolean found = false;
    while (element < N) 
    {
        if(key == arr[element]){
            found = true;
            break;
        }
        element++;
    }

    if(!found)
        {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);
}

答案 1 :(得分:0)

试试这个:

while (element < N && key != arr[element] )

这不起作用:

while (key != arr[element] && element < N )

因为当elements获得N的值时,此代码key != arr[element]仍将执行,并且调用arr[arr.length]会抛出异常。