[英]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.