【发布时间】:2018-03-07 01:34:17
【问题描述】:
我的方法应该返回一张卡片,我在 for 循环中有一个 if 语句 - 我不想在最后添加“return c”,因为这将返回卡片甲板中的最后一张卡片。我收到错误消息说“必须返回类型卡”。你有什么建议?
附:这是我的第一篇文章之一 - 如果它有一个明显的答案,我们深表歉意。所有这些括号都让我失望......
public Card findRightCardWithIndex(int index) throws IllegalArgumentException {
for(Card c:carddeck) {
if (c.getIndex() == index) {
return c;
} else {
throw new IllegalArgumentException("Invalid index");
}
}
}
【问题讨论】:
-
去掉
else。将throw移到for语句之外。否则,如果carddeck为空,该方法会返回什么? -
'return c' at the end, as that will return the last Card in carddeck会导致另一个编译错误,因为c仅在 for 循环内部定义
标签: java if-statement foreach