简体   繁体   English

每个循环中缺少return语句

[英]Missing return statement in a for each loop

I'm getting the error "Missing return statement" with this code: 我收到以下代码错误“ Missing return statement”:

public String getAuthorFullName(String title)
{
    for (Book authorName : inventory)
        if (authorName.getTitle() != null)
        {
            return authorName.getAuthor().getName().getFullName();
        } 
        else
        {
            return null;
        }
} 

I want to return o returns the full name of the author who wrote the book by this title or return null if there is no Book with this title, or if title is null or "". 我想返回o返回以该标题撰写书籍的作者的全名,如果没有带该标题的书,或者标题为null或“”,则返回null。

I tried to put the code like this: 我试图把这样的代码:

public String getAuthorFullName(String title)
{
    for (Book authorName : inventory)
        if (authorName.getTitle() != null)
        {
            return authorName.getAuthor().getName().getFullName();
        }
        return null;

But it always returns the first Author in the list... 但是它总是返回列表中的第一位作者...

Can somebody help me please? 有人可以帮我吗? Thanks a lot. 非常感谢。

Try something like this 试试这个

public String getAuthorFullName(String title)
{
    for (Book authorName : inventory) {
        if (authorName.getTitle() != null && authorName.getTitle().equals(title)) {
            return authorName.getAuthor().getName().getFullName();
        }
    }
    return null;
}

and always use braces. 并始终使用大括号。 It is much easier to live with them then without them. 与他们一起生活比没有他们容易得多。

Your first case is missing a return statement because it is. 您的第一种情况是缺少一个return语句。 Consider having an empty inventory. 考虑有一个空的库存。 So the for loop will make no runs and neither the if statement or the else statement will be executed. 因此,for循环将不运行,并且if语句或else语句都将不会执行。 And then there is no return statement left. 然后就没有返回语句了。

Your second case has a return statement that is not part of the for loop and so a correct java syntax. 第二种情况有一个return语句,该语句不是for循环的一部分,因此是正确的java语法。 BUT you only check if getTitle() != null . 但是您只检查getTitle() != null And thats true for every case a title has been set, even if it is empty. 对于每种情况,即使标题为空,也是如此。

The equality of Strings is checked with String.equals(String another) . 使用String.equals(String another)检查字符串的相等性。 So what you really want to do is: 因此,您真正想要做的是:

public String getAuthorFullName(String title){
    for (Book authorName : inventory)
        if (authorName.getTitle() != null && authorName.getTitle().equals(title))
            return authorName.getAuthor().getName().getFullName();
    return null;
}
public String getAuthorFullName(String title) {
    for (Book authorName : inventory) {
        if (authorName.getTitle() != null && authorName.getTitle().equals(title)) {
            return authorName.getAuthor().getName().getFullName();
        } 
    }
    return null;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM