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?

Dani AI

Generated

Short practical summary and a safe pattern to follow.

The exception message showing "25" is the actual index you attempted to access, not the array size. A 25-element array has valid indexes 0..24, so any user-supplied coordinate in the 1..25 range must be translated before indexing. ended up converting the parsed values and that fixed it; and pointed to the zero-based indexing cause.

Use a single, well-tested routine to convert-and-validate user coordinates so the rest of the code never directly indexes with raw input. Example (treating inputs as 1-based):

// returns true if the cell was set; prints a helpful message if out of range
public boolean setCellFromUserCoords(int userRow, int userCol) {
    if (grid == null) throw new IllegalStateException("grid not initialized");
    int r = userRow - 1;
    int c = userCol - 1;
    if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) {
        System.out.printf("Invalid cell %d,%d: valid row 1..%d col 1..%d%n",
            userRow, userCol, grid.length, grid[0].length);
        return false;
    }
    grid[r][c] = true;
    return true;
}

Extra troubleshooting tips:

  • Confirm grid creation uses new boolean[rows][cols] and that you consistently treat the first index as row and second as column.
  • Print grid.length and grid[0].length while debugging.
  • Catch NumberFormatException when parsing input and loop until valid coordinates are supplied.
  • If row-1 "didn't work" earlier, check for variable shadowing or that you subtracted before using the value; centralizing conversion in one method avoids that class of bug.

Recommended Answers

All 6 Replies

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

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.

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.

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.

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.