[英]Why does my if linked list empty statement not output anything?
我正在 java 中编写游戏,并且我有一个 else 语句来检查对象链接列表的长度,如果它为空,则应在控制台中返回“You win”。 在 intelliJ 中使用断点我可以看到代码在游戏的每个刻度上都在执行,但它似乎从未将条件注册为 true。
游戏是一个简单的节奏游戏,玩家必须计时他们的按钮按下来得分,无论玩家是否错过或击中节拍,object类型的第一个实例从链表中删除,所以理论上该列表应该如果玩家赢得比赛,则为空。 并且控制台在最后一个被错过或击中后检查节拍时执行 output 一个“没有这样的元素”异常。
由此我知道代码正在执行并且链表是空的。 我还尝试了几种方法来检查链表是否为空。
public void checkBeats(){
Beat currentObject = (Beat) Game.beatLinkedList.getFirst();
//Find the x position of the current object
int currentBeatPosition = currentObject.getX();
//Condition to award points to the player if they time hitting the beat correctly
if (currentBeatPosition <= 70) {
//Add 100 to the score variable.
Player.lives -= 1;
Game.beatLinkedList.removeFirst();
for (GameObject obj : Handler.object) {
if (obj instanceof Beat) {
Handler.object.remove(obj);
break;
}
}
checkLives();
}
else if (beatLinkedList.isEmpty() == true){
System.out.println("YOU WIN");
}
}
我还使用beatLinkedList.size ==0
和其他一些,例如if null
似乎没有任何效果。 如果有人知道原因,将不胜感激。
编辑:
尝试删除else
,并将Game.beatLinkedList
更改为beatLinkedList
,因为无论如何我都在Game
class 中工作。
public void checkBeats(){
Beat currentObject = (Beat) beatLinkedList.getFirst();
//Find the x position of the current object
int currentBeatPosition = currentObject.getX();
//Condition to award points to the player if they time hitting the beat correctly
if (currentBeatPosition <= 70) {
//Add 100 to the score variable.
Player.lives -= 1;
Game.beatLinkedList.removeFirst();
for (GameObject obj : Handler.object) {
if (obj instanceof Beat) {
Handler.object.remove(obj);
break;
}
}
checkLives();
}
if (beatLinkedList.isEmpty()){
System.out.println("YOU WIN");
}
}
编辑2:
如果我将代码更改为if (beatLinkedList.size() == 1)
然后当它到达倒数第二个节拍时,你赢的消息会在控制台中打印多次,不确定当它到达 0 时会发生什么。
可能是,当列表为空时,第一个扭曲(currentBeatPosition <= 70)也是真的吗?
如果是这样,您将不会首先进入“else” if 块。
在这种情况下,只要做到
if (beatLinkedList.isEmpty() == true){
System.out.println("YOU WIN");
}
(去掉“其他”)
首先:将else if更改为和if 。 这样,它将每次检查玩家是否获胜。
其次,您在 else if 中的代码几乎在您与beatLinkedList交互的每一行中都可能是错误的(?),您键入Game。 在前。 但是,在您的 if else 中,您不使用Game.BeatlinkedList ,您只使用beatLinkedList 。 这有什么原因吗?
if (Game.beatLinkedList.isEmpty()){ //you don't need == true.
System.out.println("YOU WIN");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.