我试过了,但它说这个错误:
cannot resolve symbol
i
public Incident getNextIncident() {
if (!incidentQueue.isEmpty()) {
Incident i = incidentQueue.element();
incidentQueue.remove();
}
return i;
}
最佳答案
解释
您不能在其声明范围的之外使用变量。
您在 if
中创建了 i
,因此它会在 if
结束后立即销毁。您必须在 if
之前创建 i
。例如:
public Incident getNextIncident() {
Incident i = null;
if (!incidentQueue.isEmpty()) {
i = incidentQueue.element();
incidentQueue.remove();
}
return i;
}
然后你就可以在外面使用了,如你所见。
处理空箱
但需要注意的是,如果没有进入if
,则为null
,您应该处理这种情况:
public Incident getNextIncident() {
Incident i = null;
if (!incidentQueue.isEmpty()) {
i = incidentQueue.element();
incidentQueue.remove();
}
if (i == null) {
// TODO Handle this case ...
}
return i;
}
请注意,您也可以直接从 inside 您的 if
返回,无需在外部执行:
public Incident getNextIncident() {
if (!incidentQueue.isEmpty()) {
Incident i = incidentQueue.element();
incidentQueue.remove();
return i;
}
// TODO Handle this case ...
}
或者,以提前返回的方式稍微重写(首选样式):
public Incident getNextIncident() {
if (incidentQueue.isEmpty()) {
// TODO Handle this case ...
}
Incident i = incidentQueue.element();
incidentQueue.remove();
return i;
}
投票
请注意,队列中移除并返回第一个值的方法有一个常用名称,poll
。如果您的队列恰好是来自 Java 库的队列,而不是自定义类,它也已经具有这样的方法。
请参阅 Queue#poll 的文档:
Retrieves and removes the head of this queue, or returns null if this queue is empty.
所以除了创建这个方法,你还可以这样做
Incident head = incidentQueue.poll();
// instead of
Incident head = incidentQueue.getNextIncident();
可选
让我向您推荐一种处理由于队列为空而无法返回值的情况的现代方法。
老式的方法是返回null
,但这有很多缺点。从 Java 8 开始,我们有了 Optional
,它正是为此而创建的(请参阅其 documentation )。
public Optional<Incident> poll() {
if (incidentQueue.isEmpty()) {
return Optional.empty();
}
Incident head = incidentQueue.element();
incidentQueue.remove();
return Optional.of(head);
}
注意事项
我还建议将事件变量重命名为 incident
或 head
而不是 i
。不要缩写变量名,除非它们是众所周知的(如 http
)或者是常见的模式(如 i
、j
、 k
用于循环或 a
, b
用于数学运算)。 i
在这里只会让人感到困惑,因为它通常用作循环中的索引变量 int i
。
关于java - 无法解析符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58265561/