简体   繁体   English

winInColumn方法应该可以,但是不能。 为什么?

[英]winInColumn method should work but doesn't. Why?

I have this method for a connect 4 game so that you can win in a column. 我有用于Connect 4游戏的这种方法,因此您可以在专栏中获胜。 However I get an Index Array out of bounds exception -1. 但是我得到索引数组超出范围例外-1。 The array it goes through is 8x8 in size (private int [][] values = new int [8][8];). 它经过的数组的大小为8x8(私有int [] []值= new int [8] [8];)。

Where have i gone wrong? 我哪里出问题了?

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.");
}

In the second loop, i goes backward from 4 to 0, and in the third loop, k goes backward from i to i - 3, which can be as low as -3, hence the exception. 在第二个循环中,i从4后退到0,在第三个循环中,k从i后退到i-3,该值可低至-3,因此是例外。

I did not really try to understand your algorithm in detail, but perhaps replace k>i-4 by k>i-4 && k>=0 would do the trick... 我并没有真正尝试详细了解您的算法,但是也许用k>i-4 && k>=0替换k>i-4可以解决问题。

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

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