user149159
user149159

Reputation: 23

compiler error when successfully printing out initial gameboard for Conway's Game of Life

Last year I worked on Conway's Game of Life using Python. This year, I'm taking a Java Course. We have been going incredibly slow and I can hardly even understand the professor, so I'm kind of working ahead.

I never truly understood the concept behind the Game of Life last time I created it, so I am re-exploring it with Java. Right now, I'm just trying to print out my initial gameboard. That's working correctly, however the compiler is throwing an error at me that I cannot understand. I've tried googling to find out the answer, but several interpretations have arisen. Please help?

 public class Game {
        public static void main(String args[])    {

       int i = 0;
       int j = 0;
       int a = 0;
       int b = 5;

       int[][] gameBoard = new int[][]{
       { 1, 2, 3, 4, 5},
       { 2, 0, 0, 0, 0},
       { 3, 0, 0, 0, 0},
       { 4, 0, 0, 0, 0},
       { 5, 0, 0, 0, 0}
       };

       while(a != b)
       {
          if(j == 5)
          {
             i++;
             j = 0;
             a++;
             System.out.println();
          }

          System.out.printf("%d ",gameBoard[i][j]);

          j++;

       }
   }
}

The compiler throws this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Game.main(Game.java:30)

Upvotes: 0

Views: 38

Answers (1)

Floris
Floris

Reputation: 46435

You allow i to keep incrementing until it is bigger than 4 - and then you exceed the limits of the array. The array does t magically get bigger - you must control your index size!

I suspect that you don't (just) want the a!=b condition but also a i<5

Upvotes: 2

Related Questions