无法解析符号

我尝试了这个,但它说这个错误:


无法解析符号i


public Incident getNextIncident() {

    if (!incidentQueue.isEmpty()) {

        Incident i = incidentQueue.element();

        incidentQueue.remove();

    }

    return i;

}


MYYA
浏览 142回答 4
4回答

暮色呼如

解释您不能在声明的范围之外使用变量。你i 在里面创建if,所以一旦结束它就会被销毁if。您必须i 在. if例如:public Incident getNextIncident() {&nbsp; &nbsp; Incident i = null;&nbsp; &nbsp; if (!incidentQueue.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; i = incidentQueue.element();&nbsp; &nbsp; &nbsp; &nbsp; incidentQueue.remove();&nbsp; &nbsp; }&nbsp; &nbsp; return i;}然后你就可以在外面使用它了,如你所见。处理空箱但需要注意的是,null如果没有进入if,则应该处理这种情况:public Incident getNextIncident() {&nbsp; &nbsp; Incident i = null;&nbsp; &nbsp; if (!incidentQueue.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; i = incidentQueue.element();&nbsp; &nbsp; &nbsp; &nbsp; incidentQueue.remove();&nbsp; &nbsp; }&nbsp; &nbsp; if (i == null) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Handle this case ...&nbsp; &nbsp; }&nbsp; &nbsp; return i;}请注意,您也可以直接从您的内部返回if,无需在外部执行此操作:public Incident getNextIncident() {&nbsp; &nbsp; if (!incidentQueue.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; Incident i = incidentQueue.element();&nbsp; &nbsp; &nbsp; &nbsp; incidentQueue.remove();&nbsp; &nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; }&nbsp; &nbsp; // TODO Handle this case ...}或者,以提前返回的方式稍微重写(首选风格):public Incident getNextIncident() {&nbsp; &nbsp; if (incidentQueue.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Handle this case ...&nbsp; &nbsp; }&nbsp; &nbsp; Incident i = incidentQueue.element();&nbsp; &nbsp; incidentQueue.remove();&nbsp; &nbsp; return i;}轮询请注意,队列中用于删除并返回第一个值的方法有一个常用名称poll。如果您的队列恰好是来自 Java 库的队列,而不是自定义类,那么它也已经具有这样的方法。请参阅Queue#poll的文档:检索并删除此队列的头部,如果此队列为空,则返回 null。因此,您可以这样做,而不是创建这个方法Incident head = incidentQueue.poll();// instead ofIncident head = incidentQueue.getNextIncident();选修的让我向您建议一种现代方法来处理由于队列为空而无法返回值的情况。老式的方式是 return null,但这有很多缺点。从 Java 8 开始,我们就Optional专门为此创建了它(请参阅其文档)。public Optional<Incident> poll() {&nbsp; &nbsp; if (incidentQueue.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; return Optional.empty();&nbsp; &nbsp; }&nbsp; &nbsp; Incident head = incidentQueue.element();&nbsp; &nbsp; incidentQueue.remove();&nbsp; &nbsp; return Optional.of(head);}笔记我还建议将事件变量重命名为incidentorhead而不是i. 不要缩写变量名称,除非它们是众所周知的(例如http)或者是常见模式(例如i, j, kfor 循环或a,b用于数学运算)。i只会在这里令人困惑,因为它通常用作int i循环中的索引变量。

蓝山帝景

您Queue毫无意义地复制现有功能。您的代码(如果有效)相当于public&nbsp;Incident&nbsp;getNextIncident()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;incidentQueue.poll(); }

慕斯709654

i您在条件内声明if,因此编译器表示该行中return i;它可能不知道是什么i。您必须在以下之前声明它if:public Incident getNextIncident() {&nbsp; &nbsp; Incident i = null;&nbsp; &nbsp; if (!incidentQueue.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; i = incidentQueue.element();&nbsp; &nbsp; &nbsp; &nbsp; incidentQueue.remove();&nbsp; &nbsp; }&nbsp; &nbsp; return i;}

繁星淼淼

这应该只是一个小问题。您已在 if 块内声明了 Incident 对象。这意味着它只留在那里。当你到达该return i;部分后,它基本上不存在。您必须Incident i在 if 块外部声明。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java