searchForItemInArray in Java - Nested For Loop

56 Views Asked by At

Java says ''the type of the expression must be Array type but it resolved to Int"

I'm looking to do a nested For Loop for the solution, but any other more more elegant suggestions are also welcome.

public class ArraySearch {
    
    public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
        
        for (int i = 0; i <= needle; i++) {
            for (int j = 0; j < haystack.length; j++) {
                if (needle[i] == haystack[j]) {
                            
                }
            }
        }
        
        return -1;
    }
    
}
3

There are 3 best solutions below

1
On

needle is an Int variable so isn't part of an array.

The answer to fix the IF statement was needle == haystack[j]

3
On

It looks like you are searching index of the needle it that array. If it is true, than your code can be as follows:

 public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
    
    for (int i = 0; i <= haystack.length; i++) {
        if (needle == haystack[j]) {
           return i;             
        }
    }
    
    return -1;
}
0
On

If searching for an item in an arrray is actually what you want, then you don't need a nested for loop.

If the needle is the item that you are searching for and the haystack is the array, you need to parse the array one time, using only one for loop and check at each step if the current item is equal to the searched element.

public static int searchForItemInArray(int needle, int[] haystack) {
    for (int i = 0; i < haystack.length; i++) {
        if (needle == haystack[i]) {
            // return the position of the item in the array.
            return i;
        }
    }
    return -1;
}