[英]Why doesn't this make sense? Removing Nodes
我有接受用戶輸入並為打印和刪除目的增加一個計數器的代碼。 我添加了一些打印行,以查看鏈表和當前位置之間的計數差異,這就是我得到的結果:
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),這意味着我只是刪除了第5個元素,而我並不是說愛。 有人可以解釋並可能幫助我解決此問題嗎?
該行引發IOFB異常
System.out.println("Deleted: " + accountRecords.get(currentAccount)
+ "\n Current record is now first record.");
您已刪除了第5個元素,所以現在沒有要顯示的第5個元素(記住數組位置從0開始)
嘗試
Object obj = accountRecords.remove(currentAccount);
System.out.println("Deleted: " + obj + "\n Current record is now first record.");
我假設你已經初始化currentAccount
為accountRecords.size() - 1
和accountRecords
有5個節點。
然后, currentAccount
的值為4,您將從列表中刪除第4個元素,而accountRecords
僅包含4個元素。
然后,您嘗試從accountRecords
僅包含4個元素且有效元素索引為0..3
的列表中獲取accountRecords.get(4)
,這就是您得到此錯誤的原因。
我認為您的錯誤是您的println:
System.out.println("Deleted: " + accountRecords.get(currentAccount)
+ "\n Current record is now first record.");
<-您收到IndexOutOfBoundsException,因為您刪除了列表的最后一個條目,否則我錯了? 也許嘗試:
System.out.println(“已刪除:” + accountRecords.get(currentAccount-1)+“ \\ n當前記錄現在是第一條記錄。”);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.