Im writing a method to return a specific record in an array however it throws up two errors and Im not sure how to fix it. Can anyone explain what I'm doing wrong?
public String find(String searchName)
{ // ERROR - MISSING RETURN STATEMENT
Iterator<TelEntry> iterator = Directory.entries.iterator();
boolean hasFound = false;
while (iterator.hasNext())
{
TelEntry entry = iterator.next();
if (entry.name.equalsIgnoreCase(searchName)) {
return entry.name + entry.telNo;
hasFound = true; // ERROR UNREACHABLE STATEMENT
}
}
if (hasFound==false)
{
System.out.println("sorry, there is noone by that name in the Directory. Check your spelling and try again");
}
}
Can anyone explain what I've done wrong?
The basic problem you have is that when a match is not found, you have no return statement. Usually, a method will return
null
is such cases, but you may want to returnsearchName
, or even the error message - it depends on what the intention/contract of the method is (not stated).However, the other problem you have is that your code is way too complicated for what it's doing, especially the
hasFound
variable is completely useless.Change your code to this, which does exactly the same thing but is expressed more elegantly: