我有这个方法用于连接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.");
}
答案 0 :(得分:0)
在第二个循环中,i从4向后移动,在第三个循环中,k从i向后移动到i-3,可以低至-3,因此是例外。
我并没有真正尝试详细了解您的算法,但可能会k>i-4
替换k>i-4 && k>=0
这样做诀窍......