简体   繁体   English

数组索引越界java

[英]array index out of bound java

Let's say numberTracker = {1,15,6,8} and numberString = {1,1,5,6,8} .假设numberTracker = {1,15,6,8}numberString = {1,1,5,6,8} Each number in numberString has its own tile. numberString每个数字都有自己的图块。 I'm try to set for example 1,5 to the same tile color since it is equal to 15 in numberTracker while tileIterator contains the same length as numberString .The code works perfectly and does what is is suppost to do.我尝试例如1,5相同的瓷砖颜色集,因为它等于15 numberTrackertileIterator含有相同的长度, numberString .The代码工作完美,做什么是suppost做。 However I get java.lang.IndexOutOfBoundsException: Index: 5, Size: 5但是我得到java.lang.IndexOutOfBoundsException: Index: 5, Size: 5

ListIterator < String > nmbTracker = numberTracker.listIterator();
ListIterator < Tile > tileIterator = tiles.listIterator();
Tile t;

int x = 0;
int y = 0;

while (nmbTracker.hasNext()) {

    if (numberTracker.get(x).equals(numberString.get(y))) {

        t = tileIterator.next();
        t.setColor(tilePanel2.changeColour());
        if (numberTracker.size() - 1 != x) {
            x++;
        }
        if (numberString.size() - 1 != y) {
            y++;
        }


    } else {
        x++;
        t = tileIterator.next();
        t.setColor(tilePanel2.changeColour());
        Color color = t.getColor();
        t = tileIterator.next();
        t.setColor(color);
        y++;
        y++;


    }

    repaint();
}

Well.好。 That is what happens when you try to access index 5 in a list that has 4 elements in it.当您尝试访问包含 4 个元素的列表中的索引 5 时,就会发生这种情况。 You are using the iterator's hasNext() to see if there are any next values available, yet you switch over to using get(x) to access the list values.您正在使用迭代器的hasNext()来查看是否有任何可用的next值,但您切换到使用get(x)来访问列表值。 Pick one .选一个

If you want to stick to the get(x) , get rid of the hasNext() and replace it with while(x<4 && y<5) , so that the list accesses don't go out of bounds.如果你想坚持get(x) ,去掉hasNext()并用while(x<4 && y<5)替换它,这样列表访问就不会越界。

If you want the iterator , instead of using get(x) , use the iterator's next() method.如果你想要iterator ,而不是使用get(x) ,使用迭代器的next()方法。

Using both interchangeably is not good, at least in this case.至少在这种情况下,交替使用两者并不好。

I think this is the smoking gun:我认为这是吸烟枪:

y++;
y++;

Next time around, you'll be one more along than the list you're checking.下一次,你会比你正在检查的名单多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM