2013-03-28 33 views
0

我有一些代碼可以接受用戶輸入並增加一個計數器以用於打印和刪除目的。我加了一些打印線看計有什麼不同鏈表和當前位置之間,這是我得到了什麼:爲什麼這不合理?刪除節點

Enter a command from the list above (q to quit): 
2 
Deleted: e    e    5    $5.0 
Current record is now first record. 
4 
5 
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4 
     at java.util.LinkedList.entry(LinkedList.java:365) 
     at java.util.LinkedList.get(LinkedList.java:315) 
     at bankdata.command(bankdata.java:158) 
     at bankdata.main(bankdata.java:314) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 18 seconds) 

輸入命令2,刪除當前節點的命令。當前節點是鏈表中的最後一個,其大小爲5,技術上意味着從0到4。

那爲什麼當我運行這段代碼:

//currentAccount is a static int that was created at the start of my code. 
//It got it's size because the int is saved every time a new node is made. 
//The most recent size correlates with the last position in the linked list. 
      int altefucseyegiv = accountRecords.size(); 
      System.out.println("Deleted: " + accountRecords.get(currentAccount) 
        + "\n Current record is now first record."); 
      System.out.println(currentAccount); 
      System.out.println(accountRecords.size()); 
      accountRecords.remove(currentAccount); 
      System.out.println("Deleted: " + accountRecords.get(currentAccount) 
        + "\n Current record is now first record."); 
      if(altefucseyegiv == 1) 
      { 
       currentAccount = -1; 
      } 
      else 
      { 
       currentAccount = 0; 
      } 
      records.currentAcc(currentAccount, accountRecords); 
      return; 

我得到這個錯誤???

我很困惑!因爲我刪除.get(4)th,這意味着我只是刪除第五個元素,我不是說愛。有人可以解釋,並可能幫助我解決這個問題嗎?

+0

是的,您可以在打印索引時訪問此元素。但是你打電話:'accountRecords.remove(currentAccount);'。嘗試輸出當前索引和大小後,可能會有助於理解問題。 –

+0

我用一個catch來檢查這個異常,我仍然有相同的大小:/ –

+0

最重要的是,如果我將currentAccount大小減1,那麼它不會刪除最後一個節點,而是最後一個節點之前的那個節點不會刪除最後一個節點。 –

回答

3

嘗試

Object obj = accountRecords.remove(currentAccount); 
System.out.println("Deleted: " + obj + "\n Current record is now first record."); 

我假設你已初始化​​爲accountRecords.size() - 1accountRecords有5個節點。

然後​​的值爲4,並且您將從列表中刪除第4個元素,而僅留下4個元素的accountRecords

那麼你正試圖從列表中獲取其中accountRecords只有4個要素和有效的元素索引0..3,這就是爲什麼你所得到的錯誤。

+0

這是有條件的,但如果你知道達利克是什麼,那麼我會在他們的聲音中讀到這個:解釋! EXPLAAAAAIN! –

+0

因爲這有效。 –

1

,我認爲你的錯誤是你的println:

System.out.println("Deleted: " + accountRecords.get(currentAccount) 
       + "\n Current record is now first record."); 

< - 你的IndexOutOfBoundsException異常,因爲你刪除列表中的最後一項,還是我錯了? 也許嘗試:
System.out.println(「刪除:」+ accountRecords.get(currentAccount-1) +「\ n當前記錄現在是第一個記錄。

+0

鏈接列表沒有null結束值像我不認爲的陣列。它們具有空連接符,但不包含位於最後的完整空節點。唯一我所知道的就是那種頭腦不平衡。 –

4

的IOFB異常是由線

System.out.println("Deleted: " + accountRecords.get(currentAccount) 
       + "\n Current record is now first record."); 

您已刪除了5個元素拋出,所以現在不存在第5個元素顯示(記住數組位置0開始)

+0

Oic。 OH IC!好!這是我敢打賭,我注意到,如果我更清醒XD謝謝哈哈! –