I’m trying to figure out how to create a method to find a string inside an array and print that string out along with its index. I think the method signature is correct but I can’t figure out how to return the string value in the method.
String name = search(array,"Dog"); //the method implementation in main
System.out.println(name);
.
public static int search(String[] array, String key)
{
for (int i= 0; i< array.length; i++)
{
if ( array[i] == key )
return i;
}
return ("Name cannot be found in array);
}
You can’t return a
Stringfrom a method that is declared to returnint. The most common ways to indicate failure are to return an out-of-range value:Or to throw an exception:
Also, this line won’t work:
Strings need to be compared with
equals(), not==. The==operator checks that the strings are the same objects, not that their contents are identical.And make sure that you don’t call
.equals()on a null reference. The above code checks for this possibility.