# [Problem] Enhanced for-loop with 2D arrays (or array in array)

• 10-07-2012, 08:49 PM
thewrongsyntax
[Problem] Enhanced for-loop with 2D arrays (or array in array)
SOLVED : I m stupid I had to write this line for(int i=0;i<=forbiddenloc.length-1;i++) {
Because the array starts from 0 and length starts counting from 1 I guess.
Code:

```        public void keyPressed(KeyEvent e) {                         boolean allowedposition=true;                         int keyCode = e.getKeyCode();                         if(keyCode == KeyEvent.VK_ESCAPE) {                                 stop();                         }else if(keyCode == KeyEvent.VK_DOWN && y<=704){                         for(int i=0;i<=forbiddenloc.length;i++) {                                         i[U]f(x==Integ[/U]er.parseInt(forbiddenloc[i][0]) && y+32==Integer.parseInt(forbiddenloc[i][1])) {                                                 allowedposition=false;                                         }                                 }                                 if(allowedposition==true) {                                         y+=32;                                 }                       }                       ...             }```
Anyway , if someone else has a better way to go trough 2D-array with a loop , please share ...
• 12-25-2013, 06:23 AM
zFollette
Re: [Problem] Enhanced for-loop with 2D arrays (or array in array)
You are going through it right, but let me explain the problem, length indicates how many items are in a collection, index starts counting at 0, so an array with a length of 50 is really only 0-49. So your for loop counts to '<=' length. You are looking for something in the 50th index of an array, which doesn't exist. You need to be using '<'. But subtracting one from the length works as well.

EDIT: By the way, this is not an advanced for loop, and advanced for loop only allows you to iterate through a collection from start to finish and does not provide index. Here is an example:

Code:

```String[] lines = new String[10]; for (String line : lines) { //Stuff }```
• 12-28-2013, 07:27 PM
jim829
Re: [Problem] Enhanced for-loop with 2D arrays (or array in array)
Do you realize this thread is over a year old? I doubt the OP still needs to resolve this.

Regards,
Jim
• 12-28-2013, 10:39 PM
JosAH
Re: [Problem] Enhanced for-loop with 2D arrays (or array in array)
Quote:

Originally Posted by jim829
Do you realize this thread is over a year old? I doubt the OP still needs to resolve this.

I'm closing it before this zombie thread is resurrected again.

kind regards,

Jos