简体   繁体   English

处理用户输入时出现ArrayList IndexOutOfBoundsException

[英]ArrayList IndexOutOfBoundsException while processing user input

I am trying to write a program that uses a sentinal contolled do-while loop, that repeatedly asks the user for positive integers. 我正在尝试编写一个使用信标控制的do-while循环的程序,该循环反复要求用户输入正整数。

The loop should end when a negative value is entered by the user. 用户输入负值时,循环应结束。 After the loop completes, your program should print out the minimum, maximum, average, and count of the positive numbers that were entered by the user. 循环完成后,您的程序应打印出用户输入的正数的最小值,最大值,平均值和计数。

However when I run the program, I get the error: 但是,当我运行程序时,出现错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at posNeg.main(posNeg.java:31)

I have searched for answers but none of them seem to be working. 我已经搜索了答案,但似乎都没有用。 Most just suggest removing the = from the for (int i = 0; i <= (count); i++) { . 大多数人只是建议从for (int i = 0; i <= (count); i++) {删除=

Anyway, here is the full code: 无论如何,这是完整的代码:

import java.util.*;
import java.lang.Math;

public class posNeg {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        ArrayList list = new ArrayList();
        int num;
        int count = 0;

        do{
            System.out.println("enter pos nums (or a neg num to quit): ");
            num = sc.nextInt();
            list.add(num);
            count++;
        } while (num >= 0);

        Iterator it = list.iterator();

        list.remove(list.get(count-1));

        Object max = Collections.max(list);
        Object min = Collections.min(list);

        System.out.print(list);

        int tot = 0;
        for (int i = 0; i <= (count); i++) {
            Object piece = list.get(i);
            int piecenum = ((Number) piece).intValue();
            tot = tot + piecenum;
        }

        double avg;
        avg = tot/count;

        System.out.println("the max is "+max+". the min is "+min+". the avg is "+avg);
    }
}

When you build your list, you increment count. 建立清单时,您要增加计数。

So after building count==list.size() . 因此,在构建count==list.size()

After that you remove one item from the listbut don't change count . 之后,您从列表中删除一项,但不要更改count

So count==list.size()-1 . 所以count==list.size()-1

So your loop should be 所以你的循环应该是

for (int i = 0; i <= count-2; i++) {

because you have items from index 0 to count-2 . 因为您有从索引0count-2

But instead of maintaining a count, you could simply do 但是,除了保持计数之外,您只需执行

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

Look at this loop: 看一下这个循环:

for (int i = 0; i <= (count); i++) {

At this point the list only has count - 1 items, but you're looping count + 1 times. 此时,列表中只有count - 1项目,但是您要循环count + 1次。 For the sake of sanity you should decrement count after the call to remove , and then also change the loop to the more idiomatic: 对于理智的缘故,你应该递减count ,来电后remove ,然后改变循环到更地道:

for (int i = 0; i < count; i++) {

Or, rather more simply: 或者,更简单地说:

for (Number number : list) {
    ...
}

This will only work after making list generic though: 不过,这仅在使list通用后才能起作用:

List<Number> list = new ArrayList<Number>();

You should really be using generics for collections. 确实应该对集合使用泛型。

Better do it this way.... 最好这样做。

for (int i = 0; i < (count); i++) {


 }

Or 要么

Use the For-Each loop 使用For-Each循环

for(Number n : list){


}

The bug is with count, as others have noted. 正如其他人所指出的那样,该错误是有价值的。 I suggest using a conditional break; 我建议使用条件break; in your input loop to avoid adding the negative value to the list, and incrementing count. 在输入循环中避免将负值添加到列表中并增加计数。 in the first place. 首先。 You will still need to replace <= with < whenever using a language with zero based indexing. 您仍需要更换<=<只要使用具有从零开始的索引的语言。

try this list.size instead of count 试试这个list.size而不是count

for (int i = 0; i < list.size(); i++) {
            Object piece = list.get(i);
            int piecenum = ((Number) piece).intValue();
            tot = tot + piecenum;
        }

Some suggestions,,, 一些建议,

    do{
        System.out.println("enter pos nums (or a neg num to quit): ");
        num = sc.nextInt();
        if (num >= 0)
           break;
        list.add(num);
    }while (true);

.. and for the next loop ..和下一个循环

    int tot = 0;
    for (int i : list ) {
        //do your stuff
    }

.. but you should really use a typed list ..但您实际上应该使用类型列表

  List<int> list = new ArrayList<int>()

... or something like that ... 或类似的东西

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

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