在用Python编写代码时,我经常通过在循环中插入return来中断函数/方法,例如,当达到条件时,我想返回值。我注意到,如果我在Java中这样做,IDE (在本例中是Eclipse)似乎不识别return命令。例如,在这里:
protected Node getTrueParent() {
for (Edge e : this.edges) {
if (e.getNode2() == this && (!e.isPseudo())) {
Node parent = e.getNode1();
return parent;
}
}
}Eclipse指出,“此方法必须返回Node类型的结果”。我做的是错的吗?而且,parent是在for循环中声明的,所以我不能在循环之外返回它。一种方法是在开始时(即在循环之外)声明parent,但这对我来说是非常草率的。写这篇文章的合适方法是什么?
发布于 2017-02-08 13:17:02
protected Node getTrueParent() {
Node parent=null;
for (Edge e : this.edges) {
if (e.getNode2() == this && (!e.isPseudo())) {
Node parent = e.getNode1();
return parent;
}
}
return parent;
}https://stackoverflow.com/questions/42113653
复制相似问题