Results 1 to 6 of 6
- 11-25-2008, 09:08 PM #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] [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; }
java.lang.ArrayIndexOutOfBoundsException: 1
at Search.search(Search.java:142)
thanks in advance
-
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(); } } }
- 11-25-2008, 09:48 PM #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++)
Luck,
CJSLChris S.
Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.
- 11-25-2008, 10:54 PM #4
Member
- Join Date
- Nov 2008
- Posts
- 11
- Rep Power
- 0
solv'd
but it wasn't any of the solutions above
I hadJava Code:if (valid [i] = true)
I now haveJava Code:if (valid [i] == true)
-
It's far better and cleaner just to write:
Java Code:if (valid[i])
- 11-26-2008, 05:26 AM #6
Member
- Join Date
- Nov 2008
- Posts
- 11
- Rep Power
- 0
Similar Threads
-
Help. Binary Search Problem
By Krooger in forum Advanced JavaReplies: 1Last Post: 11-03-2008, 07:19 AM -
Newbie search array question
By CirKuT in forum New To JavaReplies: 19Last Post: 09-14-2008, 07:26 AM -
Problem with displaying search results from an array
By BHCluster in forum New To JavaReplies: 4Last Post: 04-24-2008, 04:34 AM -
Array Search Test
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 09:45 PM -
why is my array out of bounds?
By Phobos0001 in forum New To JavaReplies: 3Last Post: 03-24-2008, 02:20 AM
Bookmarks