Search code examples
javaarraysreturn

passing array to a method and searching for a key returns only the else condition


I am passing an integer array to a method and searching for KEY but it returns noo even if the key is present

class ArraySearch
{

    public static void main(String[] args) 
    {
        int[] arr={1,2,4,4,5};

        int k=5;

        System.out.println(findArray(arr,k));


    }

    public static String findArray( int arr[],int key)
    {
        for(int i=0;i<arr.length;i++)
        {
            //System.out.println(arr[i]);
            if(arr[i]==key)
            return "YESS";

            else
            return "NOOO";//only this part is returned even if key id found
        }
        return "hoohah";
    }




}

Solution

  • Read your code carefully. You enter the loop, then test for the first element (i=0) if it equals the key. If not (else) you return immediately without searching the rest of the array.

    To search, you have to search the entire array.

    for(int i=0;i<arr.length;i++)
    {
        if(arr[i]==key)
           return "YESS";
    }
    // if we get here we searched the entire array
    return "NOOO";