繁体   English   中英

使用扫描仪的ArrayList IndexOutOfBoundsException

[英]ArrayList IndexOutOfBoundsException using Scanner

我编写了一个程序,其中用户由扫描仪提供输入,如果输入是偶数,它将被添加到数组列表中,否则将被删除。

 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:

1 2 3 4 5

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

发生这种情况是因为说您输入了一个偶数作为第一个数字。 现在,按照您的代码,您将从列表中删除此元素。 现在列表是空的,但是在下一次迭代中,您再次尝试获取空列表的索引,因此是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);
}

暂无
暂无

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

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