【问题标题】:Why do I receive the error "This method must return a result of type ..."?为什么我会收到错误“此方法必须返回类型为 ...”的结果?
【发布时间】:2013-11-22 17:15:26
【问题描述】:

当我明确返回 Card 类型的变量“card”时,谁能看到为什么我会收到错误“此方法必须返回 Card 类型的结果”?

public Card playCard(int id){
    int i = 0;
    for (Card element : hand){
        if (i <= hand.size())
        {           
            if (element.getID() == id)
            {
                Card card = hand.get(i);
                hand.remove(i);
                return card;
            }
            else
            {
                i++;
            }

        }
        else
        {
            throw new NullPointerException("Card does not exist in     hand");
        }
    }
}

【问题讨论】:

  • 提示:你需要returnfrom所有可能的执行流程。
  • 永远不要自己抛出NullPointerException
  • @arshajii 在检查后明确地抛出NullPointerException,而不是可能进行一些昂贵的处理然后访问null,当然没问题。显式或隐式,异常应该相同(而不是InvalidArgumentException 或其他),调用者不需要关心实现细节。当然这与这个问题无关,只是评论你的“从来没有”。

标签: java


【解决方案1】:

除了一种可能的情况外,您的方法不会返回任何内容。它必须在所有可能的场景中返回一些东西(或抛出异常)。

认为你打算这样做:

public Card playCard(int id){

    for (Card element : hand) {
        if (element.getID() == id) {
            return element;
        }
    }
    throw new SomeAppropriateException("Card does not exist in     hand");
}

...但我猜了一下(因为我不知道hand 是什么,但它看起来很像List)。该代码将始终执行return 语句或抛出异常,如果不发生这些事情,就无法到达方法的末尾。

请注意,对于不是由 null 指针引起的条件抛出 NullPointerException 是一个坏主意(tm)。 (最好在您放置{} 的位置保持一致。)

【讨论】:

  • 需要注意的是,它可以抛出错误(如他/她的NPE)来代替返回值。
【解决方案2】:

正如 Tarlen 所暗示的,您的代码需要进行如下修改:

public Card playCard(int id){
    int i = 0;
    for (Card element : hand){
        if (i <= hand.size())
        {           
            if (element.getID() == id)
            {
                Card card = hand.get(i);
                hand.remove(i);
                return card;
            }
            else
            {
                i++;
            }

        }
        else
        {
            throw new NullPointerException("Card does not exist in     hand");
        }
    }
    return null;
}

我相信这将解释您的程序需要采取的所有可能路线。您总是必须跟踪在方法可以退出的任何地方返回的东西。如果它可以退出而不命中 return 语句,您将看到该错误。

【讨论】:

    【解决方案3】:

    你的方法签名是:

    public Card playCard(int id){
    

    这意味着您必须返回一个Card 对象。您的代码只有一个 return 语句,但代码中有许多路径。您必须为每个路径返回一个Card 对象

    【讨论】:

      【解决方案4】:

      这是因为如果hand 为空,则不会返回任何值。

      for 循环之后添加returnthrow

      【讨论】:

        【解决方案5】:

        对于整个方法,您需要有一个默认的return 语句(或异常/错误),或者对于代码中每个可能的执行路径,至少要有一个return 语句(或异常/错误)。现在你两个都没有。

        【讨论】:

          猜你喜欢
          • 2013-09-02
          • 1970-01-01
          • 1970-01-01
          • 2018-03-08
          • 2013-12-18
          • 2015-09-25
          • 2013-11-24
          • 1970-01-01
          相关资源
          最近更新 更多