【问题标题】:Java error: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 [duplicate]Java 错误:java.lang.IndexOutOfBoundsException:索引:1,大小:1 [重复]
【发布时间】:2015-06-18 03:57:37
【问题描述】:

这是我遇到的错误,我不知道为什么。

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

我以为是数组列表,但是当我尝试 counter + 1 时,它也不起作用。

【问题讨论】:

  • size of list 小于被访问的索引,假设size is 1, index should be 0 only not 1
  • 你调试了吗?
  • 能否提供异常堆栈跟踪?你在哪个函数中得到这个异常?
  • 不是在 dicedata.get(counter) 吗?如果有,请提供此方法代码
  • 您的问题解决了吗?

标签: java indexoutofboundsexception


【解决方案1】:

使用您提供的部分代码,您似乎在diceData ArrayList 中只有一个元素。您需要在 ArrayList 中拥有与 NUMBER_OF_SIDES 一样多的元素,这样您的循环才能在不抛出异常的情况下工作。

您可以通过打印出 diceData.size() 来检查它是否等于或大于 NUMBER_OF_SIDES。

【讨论】:

    【解决方案2】:

    您的以下代码导致问题--

       for (int col= 0; col < NUMBER_OF_SIDES; col++)
        { 
             int counter = 0;
            //Add each of the 6 letters to the die ArrayList representing 
            //the die letters by calling method addLetter in class Die 
            die.addLetter(diceData.get(counter).toString());
            counter++;
        }
    

    这背后的原因是,

    您的diceData arraylist 引用仅被实例化,但其中不包含任何值。即diceData数组列表为空。

    所以为了避免这种情况,请执行以下操作--

    for (int col= 0; col < NUMBER_OF_SIDES; col++)
        { 
             int counter = 0;
            //Add each of the 6 letters to the die ArrayList representing 
            //the die letters by calling method addLetter in class Die 
            if(!diceData.isEmpty())
             {
            die.addLetter(diceData.get(counter).toString());
            counter++;
             }
            }
    

    另外我还是不明白为什么你总是在上面的循环中初始化和递增计数器。?因为我在您的代码中没有看到任何使用它。

    【讨论】:

    • 按照他的代码,在他的构造函数中初始化为传入的值
    • diceData 不为空。异常显示大小为1,初始化为作为参数传入的arrayList。
    • 这并不能解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多