在java中搜索特定记录的数组列表

Chr*_*and 1 java return arraylist unreachable-statement

我正在编写一个方法来返回一个数组中的特定记录,但它会引发两个错误,我不知道如何解决它.谁能解释我做错了什么?

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

谁能解释我做错了什么?

Boh*_*ian 6

您遇到的基本问题是,当找不到匹配项时,您没有返回语句.通常,方法将返回null这种情况,但您可能想要返回searchName,甚至是错误消息 - 这取决于方法的意图/合同是什么(未说明).

但是,你遇到的另一个问题是你的代码太复杂了,特别是hasFound变量完全没用.

将您的代码更改为此,这完全相同,但更优雅地表达:

public String find(String searchName) {
    for (TelEntry entry : Directory.entries) {
        if (entry.name.equalsIgnoreCase(searchName)) {
            return entry.name + entry.telNo;
        }
    }
    System.out.println("sorry, there is noone by that name in the Directory. Check your spelling and try again");
    return null; // or return "searchName", the error message, or something else
}
Run Code Online (Sandbox Code Playgroud)