Need Java help please

  • Comp Sci
  • Thread starter Cowtipper
  • Start date
  • #1
Cowtipper
36
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?
 

Answers and Replies

  • #2
exk
119
0
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;
}
 

Suggested for: Need Java help please

Replies
2
Views
585
  • Last Post
Replies
1
Views
171
Replies
13
Views
541
  • Last Post
Replies
5
Views
1K
  • Last Post
Replies
7
Views
663
Replies
17
Views
599
Replies
20
Views
1K
  • Last Post
Replies
1
Views
339
  • Last Post
Replies
11
Views
687
  • Last Post
Replies
4
Views
427
Top