2012-12-07 37 views
0

因此,我正在编写的某些代码中出现索引越界异常。我不明白的是,我知道我试图使用的索引元素存在。ArrayList和IndexOutOfBounds异常

下面的代码:

我有一个构造一个数组列表

public StixBoard(int number) 
{ 
    stixGame = new ArrayList<Integer>(number); 

    for (int i = 0; i < number; i++) 
    { 
     stixGame.add(i); 
    } 

} 

此块生成一个随机变量1-3

public int computeMove() 
{ 

    int numberOfStix = (int) (3.0 * Math.random()) + 1; 

    return numberOfStix; 
} 

真的直线前进,现在我在这里有一个方法需要提供参数并尝试从数组列表中删除这些数量的元素。如您所见,参数必须介于1和3之间,并且必须小于或等于数组列表的大小。否则,系统会提示用户输入另一个号码

public boolean takeStix(int number) 
{ 
    boolean logicVar = false; 
    placeHolder = stixGame.size(); 

    if ((number >= 1 && number <= 3) && number <= placeHolder) 
    { 
     for (int i = 0; i < number; i++) 
     { 
      stixGame.remove(i); 
      logicVar = true; 
     } 
    } else if (number > 3 || number > placeHolder) 
    { 
     do 
     { 
      System.out 
        .println("Please enter a different number, less than or equal to three."); 
      Scanner numberScan = new Scanner(System.in); 
      number = numberScan.nextInt(); 
     } while (number > 3 || number > placeHolder); 
    } 

    return logicVar; 
} 

因此,作为该程序运行时,computeMove()方法生成一个随机INT(假设电脑玩家的角色),并试图将该值转换为数字索引要从数组列表中删除。

这最终使我想到这一点:

How many stix on the table? 4 
|||||||||| 4 stix on the table 
It's the computer's turn! 
The computer chose 3 

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 
at java.util.ArrayList.RangeCheck(ArrayList.java:547) 
at java.util.ArrayList.remove(ArrayList.java:387) 
at StixBoard.takeStix(StixBoard.java:38) 
at StixGame.main(StixGame.java:55) 

因此,大家可以看到,数组列表的大小为4,但是在笔记本计算机掷出3,(这应该离开我1),我我留下了这个错误。我的数组列表如何从4号索引变成2号?

+5

你“知道的事实”是不正确的,如果你得到这个异常;)使用调试器,一步一步通过你的代码。 –

+0

哦,哦。我的其他语句是垃圾。 如果语句(数字> = 3)和(数字> pl​​aceHolder)到目前为止它似乎正在工作...我将最终打破else if语句来继续测试。不知道如何关闭主题 – UvrD

+0

正确你是布赖恩,我以为我看到代码正常工作,但显然我不是 – UvrD

回答

6

您遍历列表,从开始到结束,并在每一步中删除元素。这使列表中的所有元素都向左移动。

第一次迭代中:i = 0

[1, 2, 3] 

第二次迭代中:i = 1

[2, 3] 

第三次迭代中:i = 2

[2] -> IndexOutOfBoudsException. There is no index 2 in this list. 

从端部到开始迭代代替。这将使它正确,并且更快,因为列表不必从右向左复制所有元素。

+0

我的猜测是,OP预计使用'布尔list.remove(Object)'删除棒1 3,但最终使用'Object list.remove(int)'来移除给定索引处的项目。 – rsp

+0

啊geeze我现在觉得很傻,我是在假设,因为我已经实例化了一个定义值的数组列表,它会在使用.remove()方法时生成空元素......如果我实际上甚至想要我应该刚刚使用了一个数组。感谢您的帮助,解决问题! – UvrD

2

的问题是在这个循环:

for (int i = 0; i < number; i++) 
    { 
     stixGame.remove(i); 
     logicVar = true; 
    } 

一旦你删除的元素,然后列表的大小也随之减小。如果从列表大小3开始,则在第3次迭代中,索引变为2 as initially 0 then 1 then 2,而大小变为1 as intially 3 then 2 then 1。因此IndexOutOfBoundException

试试这个:

for (int i = 0; i < number; i++){ 
     stixGame.remove(0);//remove 0th index as previous element was removed 
     logicVar = true; 
    } 
0

这样看。

当你开始你的for循环时,ArrayList的大小为x

当您拨打remove()时,您将从列表中获取一个元素。所以尺寸是x-1

但是,如果您不断增加要移除的元素,最终您将移除不再存在的索引。请记住,当您拨打remove()时,数组列表的内容会被移位。所以如果你之前有0,1,2,3并且删除了2.这个列表是0,1,3。如果你打电话remove(4)这是最初有效的,你会得到一个出境异常

相关问题