【问题标题】:Why am I getting "IndexOutOfBoundsException: Index: 2, Size: 0" error为什么我收到“IndexOutOfBoundsException:索引:2,大小:0”错误
【发布时间】: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


【解决方案1】:

在这里,您正在创建 ArrayList kill_order:
ArrayList&lt;Integer&gt; kill_order = new ArrayList&lt;Integer&gt;();

但是,跳过与该列表无关的几行,您已经尝试从中读取,而实际上从未向该列表添加任何数据:
System.out.println(kill_order.get(index) + " ");

这意味着您正在尝试获取在边界内找不到的索引,因此将抛出 ArrayIndexOutOfBoundsException

为避免这种情况,您需要像使用 circle ArrayList 一样在其中添加一些条目,然后再尝试读取它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多