TOP 10
TOP 10

Reputation: 97

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

TestInput:

5

1 2 3 4 5

Please tell me what I am doing wrong and other alternatives for this program!

Upvotes: 2

Views: 146

Answers (1)

Nicholas K
Nicholas K

Reputation: 15423

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.

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

Upvotes: 3

Related Questions