有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组Java ArrayIndexOutOfBound

我目前正在做一个学生项目,每次我遇到这个错误:ArrayIndexOutOfBoundsException: 7。有人能看到它发生在哪里以及我如何修复它吗?我知道代码看起来很凌乱,但这只是为了我。数组的大小为7

public void actionPerformed(ActionEvent e) {
    if(c >= Playerlist.length) {
        if(c >= wuerfelsummen.length) {
            c = 0;
        }
    }

    if(wuerfelsummen[c] == null) {
        c++;
    }

    wuerfelsummen[c].setText(lbl_summe.getText());
    pot.setCurrentPlayer(Playerlist[c]);

    if(c >= Playerlist.length) {
        c = 0;
    } else {
        c++;

        //ARRAY_INDEX_OUT_OF_BOUNDS ERROR !!!!!!!!!!!!!!!!!!!!
        while(wuerfelsummen[c] == null) {
            if( c <= Playerlist.length) {
                c++;
            } else {
                c = 0;
            }
        }
    }
}

共 (4) 个答案

  1. # 1 楼答案

    这个字符串有问题吗

    如果(c<;=Playerlist.length){

    什么时候

    c=玩家列表。长度

    您将有一个数组索引超出界限错误

  2. # 2 楼答案

    if(c >= Playerlist.length)
            {
                c = 0;
            }
            else
            {
                c++;
    
                //ARRAY_INDEX_OUT_OF_BOUNDS ERROR !!!!!!!!!!!!!!!!!!!!
                while(wuerfelsummen[c] == null)
    

    首先检查c是否最多是数组的最后一个索引,之后将其增加1,可能会使其超过该限制

  3. # 3 楼答案

    现在试试看,你的对比很差,在循环中:

       public void actionPerformed(ActionEvent e) {
            if(c >= Playerlist.length)
            {
                if(c >= wuerfelsummen.length)
                {
                    c = 0;
                }
            }
            System.out.println(c);
            if(wuerfelsummen[c] == null)
            {
                c++;
            }
    
            System.out.println(c);
    
    
            wuerfelsummen[c].setText(lbl_summe.getText());
            lbl_summe.setText("0");
            lbl_summe.setForeground(Color.black);
            btnWerfeln.setEnabled(true);
            pot.setCurrentPlayer(Playerlist[c]);
            if(c >= Playerlist.length)
            {
                c = 0;
            }
            else
            {
                c++;
    
                //ARRAY_INDEX_OUT_OF_BOUNDS ERROR !!!!!!!!!!!!!!!!!!!!
                while(wuerfelsummen[c] == null)
                {
                    if( c < Playerlist.length-1)
                    {
                        c++;
                    }
                    else
                    {
                        c = 0;
                        //ermittleGewinner(wuerfelsummen);
                    }
    
                }
            }
            System.out.println(c);
            //ermittleGewinner(wuerfelsummen);
    
    
    
        }
    });
    
  4. # 4 楼答案

    当前,您正在增加数组末尾的索引,导致程序超出数组的边界。所以你应该改变

    if(c <= Playerlist.length)
    {
        c++;
    }
    

    。。。去

    if(c < Playerlist.length)
    {
        c++;
    }