Stack Exchange
Why am I getting "IndexOutOfBoundsException: Index: 2, Size: 0" error
Can someone please help me understand why I am getting this error?
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:659)
    at java.util.ArrayList.get(ArrayList.java:435)
    at project1.Josephus(project1.java:25)
    at project1.main(project1.java:43)


public class project1 {
  public static int Josephus (int n, int k){
    ArrayList<Integer> circle = new ArrayList<Integer>();
    for (int p=1; p<=n; p++) {                                                 
      circle.add(p);                                                      
    }
    System.out.println("There are " + n + " people in the circle.");

    ArrayList<Integer> kill_order = new ArrayList<Integer>();
    for (int index=1; circle.size()!=1; index++){
      if (circle.size() > 1){
        index = (index + k - 1) % circle.size();
        System.out.println(kill_order.get(index) + " ");
        circle.remove(index);
      }
    }
    return circle.get(0);
  }

  public static void main(String[] args) {
    System.out.println("You should sit in seat " + Josephus(6, 2) + " if you want to survive.");
  }
}


Because you never fill kill_order.

Here, you are creating the ArrayList kill_order:
ArrayList<Integer> kill_order = new ArrayList<Integer>();
However, skipping a few lines unrelated to that list, you are already trying to read from it without never actually adding any data to that list:
System.out.println(kill_order.get(index) + " ");
This means you are trying to get an index, which cannot be found within the bounds, so an ArrayIndexOutOfBoundsException will be thrown.
To avoid it, you need to add some entries to it as you did with the circle ArrayList before trying to read from it.
