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

1. Member
Join Date
Oct 2012
Posts
1
Rep Power
0

## [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.
Java 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 ...
Last edited by thewrongsyntax; 10-07-2012 at 10:02 PM.

2. ▼ dafuq did I do?
Join Date
Dec 2013
Posts
203
Rep Power
0

## 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:

Java Code:
```String[] lines = new String[10];

for (String line : lines) {
//Stuff
}```
Last edited by zFollette; 12-25-2013 at 06:26 AM.

3. Senior Member
Join Date
Jan 2013
Location
United States
Posts
2,734
Rep Power
4

## 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

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

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