0

I am creating a basic connect 4 game in java.
For this I have created a 2d array, board[][] of size 8 * 8.

To make it look a decent game, I want to make it seem as if the player tokens fall through the column to the space just above the occupied grid.

However, the code that I have written generates an ArrayIndexOutOfBoundsException. Please check the code below and tell me where I must be going wrong.

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]=' ';
    } 
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    `for(k=1;k<=9;k++)` In here `k` can go to 8 and 9 but your array here `board[k][colno-1]` only has index up to 7. – takendarkk Mar 29 '18 at 13:46

1 Answers1

0

The Exception is generated at the line :

board[k][colno-1]=current_player_token;

Cause your for-loop start with k = 1 and end with k = 8. But your board has a size of 8, so indexes goes from 0 to 7. When you call board[8] it fails.

vincrichaud
  • 2,218
  • 17
  • 34