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!