【发布时间】:2021-02-08 06:51:36
【问题描述】:
有人可以帮我理解为什么会出现这个错误吗?
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.");
}
}
【问题讨论】:
-
因为你从不填写
kill_order。
标签: java arrays arraylist circular-list