IndexOutOfBoundsException LinkedList?

时间:2017-12-11 03:01:35

标签: java exception exception-handling indexoutofboundsexception

我不确定在浏览LinkedList时如何抛出IndexOutOfBoundsException。我有这个方法,我正在努力,显然它给了我第二个for循环中最后一个元素的错误。这发生在' int pid = customerList.get(j);'线

public double averageRating() {

    // Creates new instance of ProductArrayList, reading in from the .txt file

    // two variables for calculating average
    double count = 0;
    double average = 0;

    // Nested for-loop to cycle through each customer, grab their productHistory,
    // add it, set their ranking and count
    // what ranking they are.

    for (int i = 0; i < listOfCustomers.size(); i++) {
        double total = 0;
        LinkedList<Integer> customerList = purchaseHistory.get(i);
        for (int j = 0; i < customerList.size(); j++) {
            double tempTotal = 0;
            int pid = customerList.get(j);
            Product tempProduct = listOfProducts.get(pid);
            tempTotal = tempProduct.getPrice();

            total = tempTotal + total;

        }
        if (total <= 0) {
            listOfCustomers.get(i).setRank(0);
            count = count + 0;
        }

        if (total > 0 && total < 150) {
            listOfCustomers.get(i).setRank(1);
            count = count + 1;
        }

        if (total >= 150 && total < 300) {
            listOfCustomers.get(i).setRank(2);
            count = count + 2;
        }

        if (total >= 300 && total < 450) {
            listOfCustomers.get(i).setRank(3);
            count = count + 3;
        }

        if (total >= 450 && total < 600) {
            listOfCustomers.get(i).setRank(4);
            count = count + 4;
        }

        if (total >= 600 && total < 750) {
            listOfCustomers.get(i).setRank(5);
            count = count + 5;
        }

        if (total >= 750) {
            listOfCustomers.get(i).setRank(6);
            count = count + 6;
        }

    }

    // Calculate the average based off the count added and the total amount of
    // customers.

    average = count / listOfCustomers.size();
    System.out.println("The average ranking is: " + average);
    return average;
}

这会产生错误;

线程中的异常&#34; main&#34; java.lang.IndexOutOfBoundsException:Index:13,Size:13,at java.util.LinkedList.checkElementIndex(Unknown Source),at java.util.LinkedList.get(Unknown Source),at teama.arraylist.CustomerArrayList.averageRating(CustomerArrayList的.java:305) 在teama.Sandbox.main(Sandbox.java:20)

好像我在这个范围内?有关为什么会发生这种情况以及如何在将来阻止它的任何建议?我该如何解决?

2 个答案:

答案 0 :(得分:0)

你的for循环条件中有一个i而不是j

for (int j = 0; i < customerList.size(); j++) {

应该是:

for (int j = 0; /* Note the j here --> */ j < customerList.size(); j++) {

答案 1 :(得分:0)

要回答您的问题,您的错误就在这里:

int j = 0; i < customerList.size(); j++

您正在比较i而不是j

更好地命名迭代变量。 idxinnerIdx

另外,请注意我上面的评论。不要在链表上使用get()方法:而是使用迭代器或隐式java 8 Iterable语法(for x : xcollection) { ... }。这是O(n)操作!