为什么我收到错误“此方法必须返回类型的结果...”? [英] Why do I receive the error "This method must return a result of type ..."?
问题描述
任何人都可以看到为什么我会收到错误此方法必须返回类型卡的结果,当我清楚地返回类型为Card的变量card时?
Can anyone see why I would receive the error "This method must return a result of type Card", when I clearly returns that variable "card" which is of type 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");
}
}
}
推荐答案
除了一种可能的情况外,您的方法不会返回任何内容。它必须在所有可能的场景中返回一些内容(或抛出异常)。
Your method doesn't return anything except in one possible scenario. It has to return something (or throw an exception) in all possible scenarios.
我想你的意思是这样做:
public Card playCard(int id){
for (Card element : hand) {
if (element.getID() == id) {
return element;
}
}
throw new SomeAppropriateException("Card does not exist in hand");
}
...但我猜了一下(因为我没有知道手
是什么,但它看起来很像 List
)。该代码将始终执行 return
语句或抛出异常,如果没有这些事情发生,就无法到达方法的末尾。
...but I'm guessing a bit (as I don't know what hand
is, but it looked a lot like a List
). That code will always either execute the return
statement or throw an exception, there's no way to get to the end of the method without one of those things happening.
请注意,对于不是由 null $ c $引起的条件,抛出
NullPointerException
c>指针是一个坏主意(tm)。 (最好将一致放在 {
和}
的位置。)
Note that throwing a NullPointerException
for a condition that isn't caused by a null
pointer is a Bad Idea(tm). (It's also best to be consistent in where you put your {
and }
.)
这篇关于为什么我收到错误“此方法必须返回类型的结果...”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!