0

This is the code and add numbers and remove if the par1 or par2 is even. and give me this error

ArrayList<Integer> s;
Scanner sc=new Scanner(System.in);
Scanner sm=new Scanner(System.in);
s= new ArrayList<>();
int dorinta=sc.nextInt();
if(dorinta ==1)
    {int numere =sm.nextInt();
    for(int i=0;i<numere;i++)
    {
        Integer x=sc.nextInt();
        s.add(x);
    }
}
Random random = new Random();
while(s.size()!=0)
{int i=s.size();
    int par1 = random.nextInt(20);

    System.out.println(par1);

    if(par1 % 2==0)
    {
       s.remove(s.size());
    }
    int par2= random.nextInt(20);

    Integer j= random.nextInt(15);

    System.out.println(par2);
    if(par2 %2 ==0)
    {
        s.add(j);
    }

    System.out.println(s);
}
deadshot
  • 8,881
  • 4
  • 20
  • 39
ilie alexandru
  • 207
  • 2
  • 9
  • 3
    it means that you are attempting to get the 7th element of a list that only contains 6 elements. – Stultuske Mar 22 '21 at 11:36
  • 4
    `s.remove(s.size());` will always throw that exception. Arrays and lists in Java are 0-indexed. – QBrute Mar 22 '21 at 11:37
  • 2
    @Stultuske is right, but more generally, it means, that you are trying to access an index of the list that does not exist. e.g. index 6 does not exist, if the length of the list is 6, because the list starts at index `0`. – TreffnonX Mar 22 '21 at 11:39

1 Answers1

2

As @QBrute pointed, array and Lists are zero-indexed. That means the first element is at the zeroth index and last element at index (size()-1). Also you need to check if list is empty before removing elements.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24