使用扫描仪的ArrayList IndexOutOfBoundsException

时间:2019-01-09 06:57:04

标签: java arraylist

我编写了一个程序,其中输入是由用户通过扫描仪提供的,即使输入是均匀的,也将被添加到数组列表中,否则将被删除。

 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));
    }
 }

但是它将运行时异常表示为:

  

线程“主”中的异常IndexOutOfBounException:索引:2,大小:   2

TestInput:

5

1 2 3 4 5

请告诉我该程序在做什么以及其他替代方法!

1 个答案:

答案 0 :(得分:3)

之所以发生这种情况,是因为说您输入了一个偶数作为第一个数字。现在,按照您的代码,您将从列表中删除此元素。现在列表为空,但是在下一次迭代中,您再次尝试获取空列表的索引,因此为 IndexOutOfBounException

将逻辑更改如下:

  • 首先将所有数字存储在列表中。

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

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

或更妙的是,根本不存储奇数:

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