我正在用java创建一个基本的连接4游戏 为此我创建了一个2d数组,board [] []大小为8 * 8.
为了让它看起来像个不错的游戏,我想让它看起来好像是玩家的代币 通过列落到占用网格上方的空间。
但是,我编写的代码会生成ArrayIndexOutOfBoundsException。请检查下面的代码并告诉我哪里出错了。
int a[] = {0,0,0,0,0,0,0,0};//stores the no. of empty space in each column
char board[][] = new char [8][8];
System.out.println("\n >>>-\\/->>> ENTER THE COLUMN NUMBER : PLAYER "+current_player+" :PLAYER TOKEN :"+current_player_token);
colno=Integer.parseInt(br.readLine());
tmp=a[colno-1];
//this will do the printing and initiate the falling effect only till the time required
for (k=0 ; k<7-tmp ; k++ )//k here represents the loop control variable that determines how long the element will seem to fall until it reaches the empty space
{
System.out.print("\f");
System.out.println(" 1 2 3 4 5 6 7 8 -COLUMN");
for( i=0 ; i<8 ; i++ )
{
System.out.print(" ");
for( k=1;k<=9;k++)
System.out.print("---------");
System.out.println();
System.out.println();
System.out.print(" |");
for ( j=0 ; j<8 ; j++ )
{
System.out.print(" "+board[i][j]+" |");
}
System.out.println();
System.out.println();
}
System.out.print(" ");
for(k=1;k<=9;k++)
System.out.print("---------");
//the lines below generates an ArrayIndexOutOfBoundsException
board[k][colno-1]=current_player_token;
if(k!=0)
{
board[k-1][colno-1]=' ';
}
答案 0 :(得分:0)
异常在以下行生成:
board[k][colno-1]=current_player_token;
导致您的for循环以k = 1
开头并以k = 8
结尾。但是你的电路板的大小为8,因此索引从0到7.当你拨打board[8]
时,它会失败。