我该如何阻止这个“IndexOutOfBoundsException”问题?

时间:2013-10-02 00:38:26

标签: java libgdx

因此,我的应用程序允许用户在网格上放置块,如果用户将3个或更多块具有相同的套装或颜色排列,则会发生一些事情。当玩家放置一个区块时我会调用这个方法:

   blocks_.add(new Block(new Vector2(rect_mouse.x, rect_mouse.y), blocks_.get(0).blockID, blockCount)); 

当你将3个或更多个放在一起时,我称这些方法为:

    blocks_.removeValue(blocks_.get(left_bravo_indexNum), true);
    blocks_.removeValue(blocks_.get(center_charlie_indexNum), true);
    blocks_.removeValue(blocks_.get(right_alpha_indexNum), true);


    stack:
    Exception in thread "LWJGL Application" java.lang.IndexOutOfBoundsException: 13
at com.badlogic.gdx.utils.Array.get(Array.java:125)
at com.jrp.mygearapp.GameScreen.touchUp(GameScreen.java:1443)
at com.badlogic.gdx.backends.lwjgl.LwjglInput.processEvents(LwjglInput.java:297)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:186)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:110)

这是为了删除块,但它导致了这个IndexOutOfBoundsException。有没有办法防止这个错误?

这可能是因为数组自动对元素的数量进行排序并将数字降低到数组中正确数量的元素,并且我仍然有标记高于数组大小的元素。我还是个新手,所以我的分析可能不正确。如果是这种情况请提醒我并帮助我找到解决方法。 感谢。

edirted * TouchUp()函数-------

   @Override
     public boolean touchUp(int x, int y, int pointer, int button) {

    if (button == 0)  {

        display_blockCheck = false;

        ////set blockCount to the size of blockArray so blocks can properly be indexed              
        blockCount = blocks_.size;

        if (!overlap) {

            Gdx.app.log("Block Added", "x: " + x + " y: " + y);

            updateQueueBlocks();


            //add block
            Vector2 rect_vector = new Vector2(rect_mouse.x, rect_mouse.y);
            Block block = new Block(rect_vector,blocks_.get(0).blockID, blocks_.size);

            blocks_.add(block);             

     if (center_charlie_suit == "Square") {

                center_charlie_bool = true;

                if (right_bravo_suit == "Square") {

                    right_bravo_bool = true;

                    if (right_alpha_suit == "Square") {

                        Gdx.app.log("3-pair", "Square:345:lr");

                        right_alpha_bool = true;

                        //call 3-pair event
                        blocks_.removeValue(blocks_.get(center_charlie_indexNum), true);
                        blocks_.removeValue(blocks_.get(right_alpha_indexNum), true);
                        blocks_.removeValue(blocks_.get(right_bravo_indexNum), true);
                        }
                }
            }

剩下的只是很长,只是检查彼此相邻的其他区块。

1 个答案:

答案 0 :(得分:1)

你是对的,当你删除块时,索引会改变。

你没有显示什么类型的集合blocks_(Vector2?,你写了吗?),但是,不是跟踪元素的索引,只需跟踪元素本身并调用{{1找到并删除该元素。