0

Hi all,

I have created a java program that reads in the number of rows and columns entered by the user, and creates a board of that size. Then, it takes in the position of cells (x, y) that the user wants to make live on that board. -1 will exit the program.

The program runs great, however I am running into one issue.

Say the user specifies a grid of 25 rows by 25 columns.

If the user then chooses a cell, 2 25, to make live... the following exception occurs (on the console, there are no compilation errors):

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 25
            at LifeGame.setPos
            at LifeGame.main

setPos looks like this:

 public void setPos(int x, int y)
      grid[x][y] = true

That's pretty straightforward, and I don't think it's the issue. The only thing I can think of is that it's taking in 0-24 rather than 1-25.

A simple workaround could be, after taking in x and y from the user, simply add 1 to each:

y = y + 1
x = x + 1

Edit: On second thought, this will simply change the the grid to 26 x 26. Not what I want. Is there a way to allow the user to input 1-25, rather than 0-24, for the cell positions?

Edited by needhelp88

3
Contributors
6
Replies
11
Views
4 Years
Discussion Span
Last Post by needhelp88
0

I guess you should subtract 1 instead of adding one to the variables
It should be x=x-1; and y=y-1; Now , even if user enters 2,25 . It will change to 1,24 .
Now you will not see the arrayoutofbound exception

0

Nope, still gives me the out of bounds exception. I tried that before, and logically it should work... but doesn't.

It still references setPos as the problem, which doesn't make any sense to me.

0

do you know what that exception means?
off course it's not a compile time error, since at compilation, the jvm doesn't know what values you'll pass at runtime.

0

I've solved the problem.

         int posx = Integer.parseInt(strs[0]);
         int row = posx - 1;

         int posy = Integer.parseInt(strs[1]);
         int col = posy - 1;

Not sure why it wouldn't work before.

Thanks.

0

because you had an array with 25 elements, and you were trying to acces the element with index 25.

since in Java, arrays are 0-based, that would be the (non-existant) 26th element.

0

Hi Stultuske,

Yeah, I know. But for some reason, I had to pass the values around as I did above, as using row-1 in the for loop wasn't working. Thanks.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.