问题描述
有人能帮我理解为什么我会收到这个错误吗?
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.");
}
}
解决方法
在这里,您正在创建 ArrayList kill_order
:ArrayList<Integer> kill_order = new ArrayList<Integer>();
然而,跳过与该列表无关的几行,您已经在尝试从中读取数据,而实际上从未向该列表添加任何数据:System.out.println(kill_order.get(index) + " ");
这意味着您正在尝试获取在边界内找不到的索引,因此将抛出 ArrayIndexOutOfBoundsException
。
为避免这种情况,您需要像使用 circle
ArrayList 一样在其中添加一些条目,然后再尝试读取它。