如何在Java中纠正Arraylist索引超出长度错误

时间:2019-04-02 22:07:58

标签: java arraylist indexoutofboundsexception

我正在写一个用于学校的程序,它可以用作收银机。我要输入商品的价格,并将它们播放到正在进行的ArrayList中,直到用户输入-1或0。0是为了在输入错误时重新输入以前的价格,而-1则终止循环。

我正在

  

java.lang.IndexOutOfBoundsException:索引0超出长度0的范围

尝试运行代码时出现

错误。 我必须包含一个名为removeLastEntry()的方法,该方法将在用户输入0时删除最后一次输入数组的价格。如何确保填充了阵列,并且确实删除了最后一个条目?

我正在Eclipse中运行Java 11。

在不使用该方法的情况下,代码可以正常运行,因为我减少了计数器的数量,并且在循环的下一次迭代中,无论是否删除了先前的数组位置,它都将被覆盖。该方法本身设置为删除ArrayList.size()-1,以便删除最后一个条目。我用-2和0进行了尝试,但仍然超出范围。

我阅读了之前的问题,许多人没有填充阵列。 因此,我运行了一个打印存根,以确保ArrayList已正确填充,并且具有:当将两个项目放入ArrayList的大小等于2时。错误代码还会增加我放入代码中的更多项目,但是始终是项目-1个项目超出范围的索引-1个长度 我确定我在犯一个菜鸟错误,但我找不到它,这让我发疯了!

对于完整的错误上下文:

  

线程“主”中的异常java.lang.IndexOutOfBoundsException:索引0超出长度0       在java.base / jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)       在java.base / jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)       在java.base / jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)       在java.base / java.util.Objects.checkIndex(Objects.java:372)       在java.base / java.util.ArrayList.get(ArrayList.java:458)       在C_M_iDeaProject.main(C_M_iDeaProject.java:76)

// declare our array list which will hold our prices!
ArrayList<Double> prices = new ArrayList<Double>();


// declaring variables to terminate loop, count prices, total prices, and current entry for conditions
        int counter  = 0;
        double entry = 0;
        double total = 0;

// our loop to continuously add prices to the array list from input
while (entry != -1) {

    System.out.println("Enter a price for item #" + (counter+1) + ": ");
    entry = myInput.nextDouble();

// if the entry is a price we will add it to prices and continue with the loop

    if (entry != 0 && entry != -1) {
            prices.add(entry);
            total += entry;
            counter++;
    }

//if the entry is 0 we will revert back to the previous iteration to re-add

    else if (entry == 0.0) {
        total -= prices.get(counter-1);
        removeLastEntry(prices);
        counter--;
    }

public static void removeLastEntry(ArrayList<Double> anArrayList) {
    anArrayList.remove(anArrayList.size()-1);
}

2 个答案:

答案 0 :(得分:0)

我们通过在尝试删除列表中的最后一个元素之前检查列表是否已经为空来解决此问题-以防万一您收到的第一个值是零:) 我们对原始代码进行了编辑,以封装有关约定的行为(-1退出,0删除最后一个值),并避免在每次需要检查时都违反该原则。

    List<Double> prices = new ArrayList<Double>();

    // declaring variables to terminate loop, count prices, total prices, and current entry for conditions
    int counter  = 0;
    double entry = 0;
    double total = 0;

    // our loop to continuously add prices to the array list from input
    while (!isExit(entry)) {
        System.out.println(String.format("Enter a price for item # %s: ", counter+1));
        entry = myInput.nextDouble();

    // if the entry is a price we will add it to prices and continue with the loop
        if(isExit(entry)){
            //TODO exit
        }
        if(isRemove(entry)){
            if(!list.isEmpty()){
                total -= removeLastEntry(prices);
                counter--;
            }
        }else{
            prices.add(entry);
            total += entry;
            counter++;
        }

    }

    private boolean isExit(double value){
        return value==-1;
    }

    private boolean isRemove(double entry){
        return entry==0;
    }

    public static double removeLastEntry(List<Double> list) {
        double last = list.get(list.size()-1);
        list.remove(list.size()-1)
        return last;
    }

答案 1 :(得分:0)

您可以添加支票查看if the list is empty

// declare our array list which will hold our prices!
ArrayList<Double> prices = new ArrayList<Double>();


// declaring variables to terminate loop, count prices, total prices, and current entry for conditions
        int counter  = 0;
        double entry = 0;
        double total = 0;

// our loop to continuously add prices to the array list from input
while (entry != -1) {

    System.out.println("Enter a price for item #" + (counter+1) + ": ");
    entry = myInput.nextDouble();

// if the entry is a price we will add it to prices and continue with the loop

    if (entry != 0 && entry != -1) {
            prices.add(entry);
            total += entry;
            counter++;
    }

//if the entry is 0 we will revert back to the previous iteration to re-add

    else if (entry == 0.0) {
        total -= prices.get(counter-1);
        removeLastEntry(prices);
        counter--;
    }

public static void removeLastEntry(ArrayList<Double> anArrayList) {
    if(!anArrayList.isEmpty()) {
        anArrayList.remove(anArrayList.size()-1);
    }
}