简体   繁体   English

使用扫描仪的ArrayList IndexOutOfBoundsException

[英]ArrayList IndexOutOfBoundsException using Scanner

I write a program in which the input is given by the user through scanner and if the input is even it will be added to the array list, otherwise it will be removed. 我编写了一个程序,其中用户由扫描仪提供输入,如果输入是偶数,它将被添加到数组列表中,否则将被删除。

 Scanner sc = new Scanner(System.in);
 int n = sc.nextInt();    //maximum no of elements to entered in arrayList
 int a = 2;    
 ArrayList<Integer> al = new ArrayList<Integer>();
 for(int i = 0; i < n; i++)
 {
    al.add(sc.nextInt());
    if(al.get(i) % 2 == 0)
    {
        al.remove(al.get(i));
    }
 }

But it gives run time exception as : 但是它给出了运行时异常为:

Exception in thread "main" IndexOutOfBounException: Index: 2, Size: 2 线程“主”中的异常IndexOutOfBounException:索引:2,大小:2

TestInput: TestInput:

5

1 2 3 4 5 1 2 3 4 5

Please tell me what I am doing wrong and other alternatives for this program! 请告诉我该程序在做什么以及其他替代方法!

This is happening because say you input an even number as the first number. 发生这种情况是因为说您输入了一个偶数作为第一个数字。 Now as per you code you will remove this element from the list. 现在,按照您的代码,您将从列表中删除此元素。 Now the list is empty, but in the next iteration you are again trying to fetch the index of an empty list, hence the IndexOutOfBounException . 现在列表是空的,但是在下一次迭代中,您再次尝试获取空列表的索引,因此是IndexOutOfBounException

Change the logic to as follows: 将逻辑更改为如下:

  • First store all the numbers in the list. 首先将所有数字存储在列表中。

     for (int i = 0; i < n; i++) { al.add(sc.nextInt()); } 
  • Once done remove the odd numbers. 完成后,删除奇数。

     al.removeIf(i -> i % 2 != 0); 

Or even better, don't store the odd numbers at all : 甚至更好的是,根本不存储奇数:

for (int i = 0; i < n; i++) {
    int num = sc.nextInt();
    if (num % 2 == 0)
        al.add(num);
}

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

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