簡體   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