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,这意味着我只是删除了第 5 个元素,我不是说爱。有人可以解释一下并可能帮我解决这个问题吗?

4

3 回答 3

4

IOFB 异常由行抛出

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

您已经删除了第 5 个元素,所以现在没有第 5 个元素要显示(请记住数组位置从 0 开始)

于 2013-03-28T11:54:57.413 回答
3

尝试

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

我假设您已初始化currentAccountaccountRecords.size() - 1accountRecords有 5 个节点。

然后currentAccount有一个值 4 并且您正在从列表中删除第 4 个元素,accountRecords只留下 4 个元素。

然后,您尝试从只有 4 个元素且有效元素索引为accountRecords.get(4)的列表中获取,这就是您收到错误的原因。accountRecords0..3

于 2013-03-28T11:55:32.377 回答
1

我认为你的错误是你的 println:

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

<- 你得到 IndexOutOfBoundsException 是因为你删除了列表的最后一个条目,还是我错了?也许试试:
System.out.println("Deleted: " + accountRecords.get(currentAccount-1) + "\n 当前记录现在是第一条记录。");

于 2013-03-28T11:53:53.067 回答