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

  • Context: Comp Sci 
  • Thread starter Thread starter Cowtipper
  • Start date Start date
  • Tags Tags
    Java
Click For Summary
SUMMARY

The forum discussion addresses the "method must return a result of type int" error in Java when implementing a sequential search for a string index. The original code incorrectly checks if the loop index exceeds the array length, which is logically impossible. The suggested solution simplifies the logic by breaking the loop upon finding the searched string and correctly returning the index or -1 if not found, ensuring that the method always returns an int.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with array data structures in Java
  • Knowledge of control flow statements (if, for, break) in Java
  • Experience with method return types in Java
NEXT STEPS
  • Study Java method return types and error handling
  • Learn about Java array manipulation and searching algorithms
  • Explore debugging techniques in Java to identify logical errors
  • Investigate best practices for implementing search algorithms in Java
USEFUL FOR

Java developers, software engineers, and students learning about method implementation and error resolution in Java programming.

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 ·
Replies
5
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K