0

我有这个方法用于连接 4 游戏,这样你就可以在列中获胜。但是我得到一个索引数组越界异常-1。它经过的数组大小为 8x8(private int [][] values = new int [8][8];)。

我哪里出错了?

public int winInAColumn(){
    int sum; //set sum as an integer
    for(int j=0;j<8;j++){ //loop through the rows
        for(int i=4;i>-1;i--){ //loop through columns. I must equal 4 as there must be three disks next to  
            sum = 0; //set sum to 0
            for(int k=i;k>i-4;k--){ //loop backwards through k while k is bigger than i minus 4
                sum+=values[k][j]; //sum + sum = the value in  i and j
            }
            if(Math.abs(sum)==4){
                if(sum/4 == 1){
                    if(JOptionPane.showConfirmDialog(null, "Blue Has Won", "Game over", JOptionPane.OK_CANCEL_OPTION) == 0){
                        //
                    }
                    else 
                    {
                        System.exit(0);
                    } 
                }

                else if (sum/4 == -1){
                    if(JOptionPane.showConfirmDialog(null, "Blue Has Won", "Game over", JOptionPane.OK_CANCEL_OPTION) == 0)
                    {
                        //
                    }
                    else
                    {
                        System.exit(0);
                    } 
                }
            }
        }
    }
                return 0;
        //JOptionPane.showMessageDialog(null, "No one won this time.");
}
4

1 回答 1

0

在第二个循环中,i 从 4 倒退到 0,在第三个循环中,k 从 i 倒退到 i - 3,可能低至 -3,因此例外。

我并没有真正尝试详细了解您的算法,但也许替换k>i-4k>i-4 && k>=0可以解决问题...

于 2013-03-30T18:09:22.297 回答