Help with Checking boundaries in a 2d array

Means of checking boundaries in a 2d array

Page 1 of 1

1 Replies - 2293 Views - Last Post: 09 December 2010 - 08:29 AM Rate Topic: -----

#1 greenone1975  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-December 10

Help with Checking boundaries in a 2d array

Posted 09 December 2010 - 08:06 AM

Hi,

I am currently working on a project where there is a two-dimensional 50-by-50 grid of data objects that represent a single square in the grid. This is a "playing surface" where other objects (Soldiers, recon, etc) while be moving about in sometimes random ways. Each of the soldier elements has a search loop that takes in adjacent squares in all directions and "looks" for enemies. My problem is when a soldier object gets to the edge of the grid and tries to "look" in squares that don't exist because they are beyond the "playing surface", I get an ArrayIndexOutOfBoundsException, which I understand why, but I am not sure how to fix it. I tried putting in a try catch block, but that doesn't help repeated moves. Any ideas on how I can help fix the boundaries?

Thanks,

DRW

Is This A Good Question/Topic? 0
  • +

Replies To: Help with Checking boundaries in a 2d array

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10560
  • View blog
  • Posts: 39,071
  • Joined: 27-December 08

Re: Help with Checking boundaries in a 2d array

Posted 09 December 2010 - 08:29 AM

You need to check to make sure that (x >= 0 && x < arr.length) && (y >= 0 && y < arr[x].length). Any indices outside of these bounds are illegal.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1