Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (499)
Games in Android Showcase (118)
games submitted by our members
Games in WIP (567)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  An array index out of bounds exception, I know what that means but.. why!?  (Read 3014 times)
0 Members and 1 Guest are viewing this topic.
Offline samdeman22

Junior Member


Projects: 1



« Posted 2013-07-02 20:40:17 »

So my code here checks the "neighbourhood" of a cell, my cells are simply an array of Booleans [34 * 24] a total of 816.
When I run this code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
public void function(int x, int y){
      int n = 0;
      int x1 = 0, x2 = 0, y1 = 0, y2 = 0;
      if(x == 0){
         x1 = x;
         x2 = x + 1;
      }
      if(x == pWidth){
         x1 = x - 1;
         x2 = x;
      }
      if(y == 0){
         y1 = y;
         y2 = y + 1;
      }
      if(y == pHeight){
         y1 = y - 1;
         y2 = y;
      }
      if(x != 0 && x != pWidth && y != 0 && y != pHeight){
         x1 = x - 1;
         x2 = x + 1;
         y1 = y - 1;
         y2 = y + 1;
      }
         
      for(int i = y1; i <= y2; i++){
         for(int j = x1; j <= x2; j++){
            if(pCell[j + i * pWidth] == true && j != x && i != y) n++;
         }
      }
}


I get an array index out of bounds.... on line 29 (where it looks at the array given its position) and the value after says: 816, the length of the array.

All of those if statements at the top are to make sure I don't get an array exception (for instance, by it checking the squares above and around 0,0) . pWidth and pHeight are the width and height of pCell (the array of Booleans 816 entries long). What do you see wrong? anything?

If in doubt go flat out - Collin McRae
Offline deepthought
« Reply #1 - Posted 2013-07-02 20:51:25 »

816 is the length of the array, but arrays are indexed from 0 to length-1.

jocks rule the highschools. GEEKS RULE THE WORLD MWAHAHAHA!!
captain failure test game
Offline mrdeathjockey

Senior Member


Medals: 5
Projects: 1
Exp: 3 years


Trying to be a good programmer, step by step


« Reply #2 - Posted 2013-07-03 06:41:08 »

Array indices always start at 0. So if you have any array with length of 'n', the indices are from 0 to n - 1. An array with size of 816 means that the last entry is 815. Perhaps you're trying to access a value that is either above 815 or less than 0.

So that's something to remember, also remember to put a try n' catch block for ArrayIndexOutOfBoundsException!
For more on arrays: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline philfrei
« Reply #3 - Posted 2013-07-03 07:03:36 »

I think your algorithm gets in trouble when you check if x = pWidth and y = pHeight. If your pixel array is of width pWidth and height pHeight, then you probably want to make your leftside check if (x == pWidth-1) and your bottomside check if (y == pHeight-1).

There's a couple more changes that will be needed as a result of this change, but I think you will see them.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline cylab

JGO Ninja


Medals: 50



« Reply #4 - Posted 2013-07-03 08:31:20 »

The problem is that if you have a columns that has pHeight cells the minimum y would be 0 and the maximum y would be pHeight-1. Same goes for x and pWidth. So if you set y2 to pHeight you set it to the first non-existent row after the last one, hence the AIOOBE.




Mathias - I Know What [you] Did Last Summer!
Offline samdeman22

Junior Member


Projects: 1



« Reply #5 - Posted 2013-07-04 19:21:22 »

I think your algorithm gets in trouble when you check if x = pWidth and y = pHeight. If your pixel array is of width pWidth and height pHeight, then you probably want to make your leftside check if (x == pWidth-1) and your bottomside check if (y == pHeight-1).

There's a couple more changes that will be needed as a result of this change, but I think you will see them.

right that makes sense Smiley (so how do I check the last one!? I added an if statement so it basically skips the last one, but I really don't want it to do that. So what is this fix that I was supposed to find obvious?)

also... I don't want the check to count the cell(x,y), only the cells AROUND (x,y). So to stop that I added some logic to the check part.
1  
2  
3  
4  
5  
6  
7  
for(int i = y1; i <= y2; i++){
         for(int j = x1; j <= x2; j++){
            if(x != 33 && y != 23){
               if(pCell[j + i * pWidth] && (j != x) && (i != y)) n++;
            }
         }
      }


now to me this says that when the cell is true AND (x does not equal the middle cell's x AND y does not equal the middle cell's y) ... so every time except when the co-ordinates are directly ON the middle cell. But instead whenever there is a true cell on the same X as the middle or the same Y it returns false, only when there are true cells in the corners does it work (I made it to the game of life rules (myself) if you must know)

after this I just need to make the keyboard work, oh god. D:

If in doubt go flat out - Collin McRae
Offline philfrei
« Reply #6 - Posted 2013-07-04 20:29:24 »

The code as it stands is not so clear. Evidence: there's a bug and it is not easy to spot right away. So, I'd try and do things in a way that makes what is going on more explicit.

One idea is that since you have special cases with your algorithm when you are on an edge, try making the edges more obvious.

1  
2  
3  
4  
    int leftEdge = 0;
    int rightEdge = pWidth - 1;
    int topEdge = 0;
    int bottomEdge = pHeight - 1;

Now, use these values to assign your x1, x2, y1, y2. All in all pretty verbose, but I think it might help make OBO errors (off-by-one errors) easier to spot.

But maybe a better alternative would be to make the edge-condition test part of the for loop. Then you don't have the "complication" of building different for-loops.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
for (int j = y-1; j <= y+1; y++)
{
    for (int i = x-1; i <= x+1: x++)
    {
        if (( i >= 0 ) && ( i < pWidth ) && ( j >= 0 ) && ( j < pHeight )
                && ( i != x && j != y) )
        {
            if ( pCell[j + i * pWidth] ) n++;
        }
    }
}


Is that better? I'm not sure. But at least the edge case tests are all grouped together. And the "qualifying tests" are separated from the counting test. The "qualifying" tests could also then be further consolidated.
1  
2  
3  
4  
    boolean isWithinP(int x, int y)
    {
         return ( x >= 0 ) && ( x < pWidth ) && ( y >= 0 ) && ( y < pHeight );
    }

Then, the qualifying-to-be-counted test becomes:

1  
    if (isWithinP(i, j) &&  i != x && j != y) )


Just some ideas...a lot of what determines what code is easiest to read is in the eye of the beholder and the context. The function isWithinP() is also easy to Unit Test.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline samdeman22

Junior Member


Projects: 1



« Reply #7 - Posted 2013-07-04 22:31:30 »

So my code here checks the "neighbourhood" of a cell, my cells are simply an array of Booleans [34 * 24] a total of 816.
When I run this code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
public void function(int x, int y){
      int n = 0;
      int x1 = 0, x2 = 0, y1 = 0, y2 = 0;
      if(x == 0){
         x1 = x;
         x2 = x + 1;
      }
      if(x == pWidth){
         x1 = x - 1;
         x2 = x;
      }
      if(y == 0){
         y1 = y;
         y2 = y + 1;
      }
      if(y == pHeight){
         y1 = y - 1;
         y2 = y;
      }
      if(x != 0 && x != pWidth && y != 0 && y != pHeight){
         x1 = x - 1;
         x2 = x + 1;
         y1 = y - 1;
         y2 = y + 1;
      }
         
      for(int i = y1; i <= y2; i++){
         for(int j = x1; j <= x2; j++){
            if(pCell[j + i * pWidth] == true && j != x && i != y) n++;
         }
      }
}


I get an array index out of bounds.... on line 29 (where it looks at the array given its position) and the value after says: 816, the length of the array.

All of those if statements at the top are to make sure I don't get an array exception (for instance, by it checking the squares above and around 0,0) . pWidth and pHeight are the width and height of pCell (the array of Booleans 816 entries long). What do you see wrong? anything?

that's an idea, I'm sure I would get the last value thing eventually, but since I've never done this before its not obvious. I don't really know how to make eclipse track variables in debug mode, I find them sometimes when the variables are part of the line that gives the error, but it would be really helpful if I could know what all the variables are. Is that possible?
I tried this condition loop before and it was even longer, if statements everywhere, this is my shortest one Cheesy ill try some of what you said.

If in doubt go flat out - Collin McRae
Offline samdeman22

Junior Member


Projects: 1



« Reply #8 - Posted 2013-07-04 22:47:19 »

wrong quote XD

If in doubt go flat out - Collin McRae
Offline Oskuro

JGO Knight


Medals: 39
Exp: 6 years


Coding in Style


« Reply #9 - Posted 2013-07-05 11:29:20 »

It'll probably help to make a mental distinction between array size and array bounds.

·Size: Number of elements contained by the array
·Bounds: Range of valid identifiers for the contained elements.

This distinction will become vital if you need to implement variable size data structures, like lists, stacks or queues, whose array size does not necessarily match the actual bounds.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline samdeman22

Junior Member


Projects: 1



« Reply #10 - Posted 2013-07-05 18:04:19 »

The code as it stands is not so clear. Evidence: there's a bug and it is not easy to spot right away. So, I'd try and do things in a way that makes what is going on more explicit.

One idea is that since you have special cases with your algorithm when you are on an edge, try making the edges more obvious.

1  
2  
3  
4  
    int leftEdge = 0;
    int rightEdge = pWidth - 1;
    int topEdge = 0;
    int bottomEdge = pHeight - 1;

Now, use these values to assign your x1, x2, y1, y2. All in all pretty verbose, but I think it might help make OBO errors (off-by-one errors) easier to spot.

But maybe a better alternative would be to make the edge-condition test part of the for loop. Then you don't have the "complication" of building different for-loops.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
for (int j = y-1; j <= y+1; y++)
{
    for (int i = x-1; i <= x+1: x++)
    {
        if (( i >= 0 ) && ( i < pWidth ) && ( j >= 0 ) && ( j < pHeight )
                && ( i != x && j != y) )
        {
            if ( pCell[j + i * pWidth] ) n++;
        }
    }
}


Is that better? I'm not sure. But at least the edge case tests are all grouped together. And the "qualifying tests" are separated from the counting test. The "qualifying" tests could also then be further consolidated.
1  
2  
3  
4  
    boolean isWithinP(int x, int y)
    {
         return ( x >= 0 ) && ( x < pWidth ) && ( y >= 0 ) && ( y < pHeight );
    }

Then, the qualifying-to-be-counted test becomes:

1  
    if (isWithinP(i, j) &&  i != x && j != y) )


Just some ideas...a lot of what determines what code is easiest to read is in the eye of the beholder and the context. The function isWithinP() is also easy to Unit Test.

yeah, organising it did fix the silly AIOOB but it still cant detect when there is a live cell on the same X or Y as the middle, it still only picks up the corners. The logic looks perfect (this is following both mine and yours). If its inside(j, i) AND i does not equal y AND j does not equall X, whats wrong with that!? It skips the line entirely if i = y OR j = x, instead of AND.
1  
if(isInside(j,i) && ((j != x) && (i != y)))

If in doubt go flat out - Collin McRae
Offline philfrei
« Reply #11 - Posted 2013-07-07 04:49:32 »

 Grin You are reminding me of a course I took in college, decades ago, on logic for circuit design. I recall there were interesting ways "not and" could be set up to be the equivalent of "or"; or "not or" used for "and". We had assignments where we had to use just "nand" or just "nor" gate IC's (with negations allowed as well).

The best way to find the correct answer might be to just work out the "truth table" by hand.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline Abuse

JGO Knight


Medals: 12


falling into the abyss of reality


« Reply #12 - Posted 2013-07-07 10:10:42 »

With a debugger you should be able to make sense of even the most obtuse code.
Stick a break point on the Exception in question, and investigate the state of all the relevant variables at the point the error occurs.

That said, if you can't understand your own code, what chance do others have?

Always endeavor to write code that'll be understandable to others, and yourself 6 months down the line!

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline samdeman22

Junior Member


Projects: 1



« Reply #13 - Posted 2013-07-07 18:03:45 »

well, thank you for the help I guess,  Grin I fixed the logic problem by simply saying if the cell I'm checking is true, take away one from the number of surrounding cells. And now, I have my very own Game of life!

With a debugger you should be able to make sense of even the most obtuse code.
Stick a break point on the Exception in question, and investigate the state of all the relevant variables at the point the error occurs.

That said, if you can't understand your own code, what chance do others have?

Always endeavor to write code that'll be understandable to others, and yourself 6 months down the line!

Try telling that to the people who make examples in the official oracle documentation. If I could understand what they wrote, I'm sure I'd come to forums less often  Undecided


If in doubt go flat out - Collin McRae
Offline philfrei
« Reply #14 - Posted 2013-07-08 07:00:07 »

you're welcome I guess... Tongue

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline HeroesGraveDev

JGO Kernel


Medals: 260
Projects: 11
Exp: 2 years


┬─┬ノ(ಠ_ಠノ)(╯°□°)╯︵ ┻━┻


« Reply #15 - Posted 2013-07-08 07:09:25 »

Making all the logic gates out of nor gates is fun. Cheesy

Offline TrinityGamer

Senior Newbie


Medals: 2



« Reply #16 - Posted 2013-07-08 08:17:13 »

With a debugger you should be able to make sense of even the most obtuse code.
Stick a break point on the Exception in question, and investigate the state of all the relevant variables at the point the error occurs.

That said, if you can't understand your own code, what chance do others have?

Always endeavor to write code that'll be understandable to others, and yourself 6 months down the line!

if that was true, then people wouldn't use the help forum, as there would be no point. sometimes people make mistakes and can't notice them themselves, so they need us (the community Cheesy) to help them. Smiley Besides, we're all friends here, and more then willing to help. :3
Offline Oskuro

JGO Knight


Medals: 39
Exp: 6 years


Coding in Style


« Reply #17 - Posted 2013-07-08 10:18:10 »

I agree with you, TrinityGamer, but it is also true that some people will not even try to solve the problem themselves before asking for help, so it is always good to remind people that the power is in their own hands.

Also, the community is helpful, but we're not tech support.  Tongue

Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 133
Projects: 4
Exp: 3 years



« Reply #18 - Posted 2013-07-08 12:04:07 »

well, thank you for the help I guess,  Grin I fixed the logic problem by simply saying if the cell I'm checking is true, take away one from the number of surrounding cells. And now, I have my very own Game of life!

With a debugger you should be able to make sense of even the most obtuse code.
Stick a break point on the Exception in question, and investigate the state of all the relevant variables at the point the error occurs.

That said, if you can't understand your own code, what chance do others have?

Always endeavor to write code that'll be understandable to others, and yourself 6 months down the line!

Try telling that to the people who make examples in the official oracle documentation. If I could understand what they wrote, I'm sure I'd come to forums less often  Undecided


Be grateful there are examples. If you start using a library like libGDX you're going to find a lot less and more inconsistent examples, if they exist at all. Oracle has done a pretty good job with their documentation and tutorials, but in the end it's up to you to implement whatever you need. If the Oracle examples confuse you, use Google and find another one, not that complicated.
Offline Abuse

JGO Knight


Medals: 12


falling into the abyss of reality


« Reply #19 - Posted 2013-07-09 11:10:09 »

With a debugger you should be able to make sense of even the most obtuse code.
Stick a break point on the Exception in question, and investigate the state of all the relevant variables at the point the error occurs.

That said, if you can't understand your own code, what chance do others have?

Always endeavor to write code that'll be understandable to others, and yourself 6 months down the line!

if that was true, then people wouldn't use the help forum, as there would be no point. sometimes people make mistakes and can't notice them themselves, so they need us (the community Cheesy) to help them. Smiley Besides, we're all friends here, and more then willing to help. :3

I wasn't meaning to chastise the OP for asking a question he should have been able to answer himself; I was suggestion the course of action I'd take to resolving his problem*.

*Assuming I had the time & motivation to download his code, paste it into Eclipse, run it to the point it crashes, and analyse how what it's doing differs from what it's supposed to be doing.

Glad to hear the OP resolved his issue.

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline samdeman22

Junior Member


Projects: 1



« Reply #20 - Posted 2013-07-15 18:02:18 »

Be grateful there are examples. If you start using a library like libGDX you're going to find a lot less and more inconsistent examples, if they exist at all. Oracle has done a pretty good job with their documentation and tutorials, but in the end it's up to you to implement whatever you need. If the Oracle examples confuse you, use Google and find another one, not that complicated.

No doubt it IS actually useful in more advanced stages, but for a beginner like me?  Undecided
I could go on youtube tutorials, and that is what I've done up until now, but I don't want to follow a tutorial f you know what I mean.

If in doubt go flat out - Collin McRae
Offline samdeman22

Junior Member


Projects: 1



« Reply #21 - Posted 2013-07-15 18:04:32 »

ONE final problem, I'm sure it can be fixed with one line of code. How do I make it so that the keyboard automatically works without me having to click in the window?

If in doubt go flat out - Collin McRae
Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 133
Projects: 4
Exp: 3 years



« Reply #22 - Posted 2013-07-15 18:16:01 »

ONE final problem, I'm sure it can be fixed with one line of code. How do I make it so that the keyboard automatically works without me having to click in the window?
What do you mean by the keyboard automatically working? Detecting key presses? (that's not possible)
Offline samdeman22

Junior Member


Projects: 1



« Reply #23 - Posted 2013-07-15 18:19:10 »

I have a key listener, listening for: enter, shift and control. The window IS the active window upon startup, but before the keyListener can actually pick up anything I have to click the canvas (inside the borders).

If in doubt go flat out - Collin McRae
Offline deepthought
« Reply #24 - Posted 2013-07-15 22:14:51 »

call requestfocus() on the canvas

jocks rule the highschools. GEEKS RULE THE WORLD MWAHAHAHA!!
captain failure test game
Offline samdeman22

Junior Member


Projects: 1



« Reply #25 - Posted 2013-07-16 16:46:24 »

call requestfocus() on the canvas

The class with main in it, "Game", extends canvas and never actually uses it anywhere else. Should it be on the JFrame instead? because that doesn't work.   Huh

If in doubt go flat out - Collin McRae
Offline samdeman22

Junior Member


Projects: 1



« Reply #26 - Posted 2013-07-16 16:49:11 »

OK I'm being silly it extends canvas so it can use things like the mouse and bufferstrategies, how would I use the requestFocus() on the Canvas then?

If in doubt go flat out - Collin McRae
Offline deepthought
« Reply #27 - Posted 2013-07-16 18:07:17 »

in this case just put
1  
requestFocus();

in your initialization code

jocks rule the highschools. GEEKS RULE THE WORLD MWAHAHAHA!!
captain failure test game
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Pippogeek (39 views)
2014-09-24 16:13:29

Pippogeek (30 views)
2014-09-24 16:12:22

Pippogeek (19 views)
2014-09-24 16:12:06

Grunnt (45 views)
2014-09-23 14:38:19

radar3301 (27 views)
2014-09-21 23:33:17

BurntPizza (63 views)
2014-09-21 02:42:18

BurntPizza (33 views)
2014-09-21 01:30:30

moogie (41 views)
2014-09-21 00:26:15

UprightPath (50 views)
2014-09-20 20:14:06

BurntPizza (54 views)
2014-09-19 03:14:18
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!