[SOLVED] Search problem - array out of bounds

• 11-25-2008, 09:08 PM
viper110110
[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.

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] [0].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)

• 11-25-2008, 09:44 PM
Fubarable
Use the array's own lengths to help you avoid going out of bounds:
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();     }   } }```
• 11-25-2008, 09:48 PM
CJSLMAN
Question...
Why is there a "length-1" in your for cycle if your looping through the valid array?
Code:

`for (int i = 0 ; i < length - 1; i++)`
... besides, I agree with Fubarable's suggestion

Luck,
CJSL
• 11-25-2008, 10:54 PM
viper110110
solv'd

but it wasn't any of the solutions above

Code:

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

I now have
Code:

`if (valid [i] == true)`
and now it works
• 11-26-2008, 05:14 AM
Fubarable
It's far better and cleaner just to write:
Code:

`if (valid[i])`
• 11-26-2008, 05:26 AM
viper110110
Quote:

Originally Posted by Fubarable
It's far better and cleaner just to write:
Code:

`if (valid[i])`

thanks, I'll remember that one