# Thread: [SOLVED] Search problem - array out of bounds

1. Member Join Date
Nov 2008
Posts
11
Rep Power
0

## [SOLVED] Search problem - array out of bounds

Hey guys, I am trying to make a search for a 2D array. I am using a program called "Ready To Program Java" (school assignment). My 1D searches using my logic work exactly as planned, however my 2D does not.

Java Code:
```public static String[] [] search (String searchFor, String word[] [], int length, int width)
{
boolean[] valid;
valid = new boolean [length];
int found = 0, j = 0;

for (int i = 0 ; i < length ; i++)
{
valid [i] = false;
}
for (int i = 0 ; i < length ; i++)
{
//for (int k = 0 ; k < width ; k++)
//{
if (word [i] .compareTo (searchFor) == 0)
{
valid [i] = true;
found++;
//k = width;
}
//}
}

String results[] [] = new String [found] [width];

for (int i = 0 ; i < length - 1; i++)
{
//for (int k = 0 ; k < width ; k++)
//{
if (valid [i] = true)
{
results [j] = word [i];
j++;
}
//}
}
return results;
}```
it is returning the error

java.lang.ArrayIndexOutOfBoundsException: 1
at Search.search(Search.java:142)  Reply With Quote

2. ## Use the array's own lengths to help you avoid going out of bounds:
Java Code:
```public class Fubar
{

public static void main(String[] args)
{
int[][] my2dArray =
{
{1, 2, 3},
{5, 7, 2},
{0, -20, 10},
{1, 1, 1}
};

for (int i = 0; i < my2dArray.length; i++)
{
for (int j = 0; j < my2dArray[i].length; j++)
{
System.out.print(my2dArray[i][j] + ", ");
}
System.out.println();
}
}
}```  Reply With Quote

3. ## Question...

Why is there a "length-1" in your for cycle if your looping through the valid array?
Java Code:
`for (int i = 0 ; i < length - 1; i++)`
... besides, I agree with Fubarable's suggestion

Luck,
CJSL  Reply With Quote

4. Member Join Date
Nov 2008
Posts
11
Rep Power
0

## solv'd

but it wasn't any of the solutions above

Java Code:
`if (valid [i] = true)`
which made valid true no matter what

I now have
Java Code:
`if (valid [i] == true)`
and now it works  Reply With Quote

5. ## It's far better and cleaner just to write:
Java Code:
`if (valid[i])`  Reply With Quote

6. Member Join Date
Nov 2008
Posts
11
Rep Power
0

##  Originally Posted by Fubarable It's far better and cleaner just to write:
Java Code:
`if (valid[i])`
thanks, I'll remember that one  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•