简体   繁体   English

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

[英]How to correct Arraylist index out of bounds for length error in Java

I am writing a program for school which acts as a cash register. 我正在写一个学校的计划,作为收银机。 I am asking for input for prices of items and playing them into an ongoing ArrayList until the user enters -1 or 0. 0 is to re-enter the previous price in case of mistake and -1 terminates the loop. 我要求输入物品的价格并将它们播放到正在进行的ArrayList中,直到用户输入-1或0. 0是在错误的情况下重新输入先前的价格并且-1终止循环。

I am getting the 我得到了

java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0 java.lang.IndexOutOfBoundsException:索引0超出长度为0的范围

error when I try to run my code. 我尝试运行代码时出错。 I have to include a method called removeLastEntry() , which will remove the last price entered into the array upon a 0 being entered by the user. 我必须包含一个名为removeLastEntry()的方法,该方法将删除用户输入0时输入到数组中的最后一个价格。 How can I ensure the array is populated and I am indeed removing the last entry? 如何确保填充数组,我确实删除了最后一个条目?

I am running Java 11 in Eclipse. 我在Eclipse中运行Java 11。

The code runs fine without the method being used, as I reduce my counter and in the next iteration of the loop, the previous array location is overwritten, regardless whether it has been removed or not. 代码在没有使用方法的情况下运行正常,因为我减少了我的计数器,并且在循环的下一次迭代中,先前的数组位置被覆盖,无论它是否已被删除。 The method itself is set to remove ArrayList.size()-1 so that it removes the last entry. 方法本身设置为删除ArrayList.size() - 1,以便删除最后一个条目。 I have tried this with -2, and 0, and it still runs out of bounds. 我用-2和0试过这个,它仍然用完了界限。

I read through previous questions and many people had not populated the array. 我读过以前的问题,很多人都没有填充数组。 So I ran a print stub to make sure that the ArrayList has been properly populated, and it has: when two items were placed into the ArrayList size was equal to 2. The error code also goes up the more items I place into the code but is always items - 1 index out of bounds at items - 1 length I'm sure I'm making a rookie mistake but I'm unable to find it and it is driving me insane! 所以我运行了一个打印存根,以确保ArrayList已正确填充,并且它具有:当两个项目放入ArrayList大小时等于2.错误代码也会增加我放入代码的项目但是总是项目 - 1个项目超出范围的索引 - 1长度我确定我犯了一个菜鸟错误但是我找不到它而且它让我疯了!

for full error context: 对于完整错误上下文:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.get(ArrayList.java:458) at C_M_iDeaProject.main(C_M_iDeaProject.java:76) 线程“main”中的异常java.lang.IndexOutOfBoundsException:java.base / jdk.internal中java.base / jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)的长度为0的索引0超出范围。 java.base / java.util.Objects.checkIndex(Objects.java:)中的java.base / jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)中的util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) 372)在C_M_iDeaProject.main的java.base / java.util.ArrayList.get(ArrayList.java:458)处(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);
}

We solve the issue by checking if the list is already empty before attempting to delete last element in list - just in case the first value you receive is a zero :) We edited the original code to encapsulate behaviour regarding conventions (-1 to exit, 0 to remove last value) and avoid violating that principle every time we need to check. 我们通过在尝试删除列表中的最后一个元素之前检查列表是否已经为空来解决问题 - 以防万一你收到的第一个值为零:)我们编辑了原始代码来封装有关约定的行为(-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;
    }

You can add a check to see 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM