微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我收到“IndexOutOfBoundsException: Index: 2, Size: 0”错误

如何解决为什么我收到“IndexOutOfBoundsException: Index: 2, Size: 0”错误

有人能帮我理解为什么我会收到这个错误吗?

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 一样在其中添加一些条目,然后再尝试读取它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。