Comp Sci Need Help Solving Java "Method Must Return a Result of Type Int" Error

  • Thread starter Thread starter Cowtipper
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
The "method must return a result of type int" error occurs because the code does not guarantee a return statement for all execution paths. The current implementation incorrectly checks if `i` is greater than `inOrder.length`, which is impossible within the loop. If the search string is not found, the method fails to return an integer, leading to the error. A suggested solution involves restructuring the loop to ensure a return statement is always reached, even if the search string is not found. Properly handling the return value will resolve the error and improve the method's functionality.
Cowtipper
Messages
36
Reaction score
0
This is really making me mad. I keep getting a "this method must return a result of type int" error message, but obviously I have a return statement trying to return an int. This is a program that is supposed to perform a sequential search for a string index.



public static int nameSearch(String[] inOrder, String searchedFor)
{
for (int i = 0; i < inOrder.length; i++)
{
if (searchedFor == inOrder)
{
return i;
}
else if (i > inOrder.length)
{
return -1;
}
}
}
Does anybody know what is wrong?
 
Physics news on Phys.org
Your else if condition can't occur.

The loop only runs while i < inOrder.legth and you are checking for i to be greater than your loop limit. If it doesn't find your search parameter it will return something that is not int and that's why you get the error.

Something like this might work better:

public static int nameSearch(String[] inOrder, String searchedFor)
{
for (int i = 0; i < inOrder.length; i++)
{
if (searchedFor == inOrder) break;
if (i == inOrder.length - 1) i = -1;
}
return i;
}
 

Similar threads

Replies
5
Views
3K
Replies
12
Views
2K
Replies
1
Views
2K
Replies
2
Views
1K
Replies
1
Views
2K
Replies
7
Views
2K
Replies
1
Views
1K
Replies
7
Views
2K
Back
Top