Search code examples
javaarraysalgorithmsearchsequential

Sequential Search array out of bound issue in java


I implemented a sequential search in java. But, i am facing array index out of bound exception problem.

when i enter the correct number, the program is working fine. But, when i press a number which is not within the array, the program crashes because of "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);
}
}

Solution

  • Your code as such has few issues, please look at my modified code. Should help you.

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