这是我得到的错误,我不知道为什么。Java错误:java.lang.IndexOutOfBoundsException:索引:1,大小:1
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
我认为这是数组列表,但是当我尝试counter + 1时它也没有工作。
这是我得到的错误,我不知道为什么。Java错误:java.lang.IndexOutOfBoundsException:索引:1,大小:1
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
我认为这是数组列表,但是当我尝试counter + 1时它也没有工作。
随着部分代码的提供,您看起来只有diceData
ArrayList中有一个元素。您需要在ArrayList中拥有与NUMBER_OF_SIDES
一样多的元素,以便您的循环在不抛出异常的情况下工作。
您可以通过打印diceData.size()
来查看它是否等于或大于NUMBER_OF_SIDES。
你的下面的代码将导致problem--
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
数组列表为空。
所以,为了避免这种情况做following--
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。 –
这不能解决它。 – codegeek123
'list of size'小于被访问的索引,假设'size是1,索引应该只有0不是1' –
你调试过吗? – DiSol
你能否提供堆栈跟踪与例外?你在哪个函数中得到这个异常? –