public class WordSearch5 { public static void main (String[] argv) { char[][] puzzle = { {'n', 'o', 'h', 't', 'y', 'p', 's'}, {'m', 'i', 'a', 'r', 'y', 'c', 'c'}, {'l', 'l', 'e', 'k', 's', 'a', 'h'}, {'r', 'u', 'b', 'y', 'v', 'm', 'e'}, {'e', 'h', 'h', 'a', 'l', 'l', 'm'}, {'p', 'c', 'j', 'n', 'i', 'c', 'e'}, {'r', 'e', 'e', 'k', 'b', 'i', 'p'} }; findWord (puzzle, "ruby"); } static void findWord (char[][] puzzle, String word) { // First convert the String into a char array. char[] letters = word.toCharArray (); // Now try every possible starting point in the puzzle array. boolean found = false; int i = 0; while ( (i < puzzle.length) && (! found) ) { int j = 0; while ( (j < puzzle[i].length) && (! found) ) { // Use (i,j) as the starting point. found = true; // Try to find the given word's letters. for (int k=0; (k<letters.length) && (found); k++) { if ( (j+k >= puzzle[i].length) || (letters[k] != puzzle[i][j+k]) ) { // Not a match. found = false; } } // If we went the whole length of the word, we found it. if (found) { System.out.println ("String " + word + " found in row=" + i + " col=" +j); } // Must increment j j ++; } // Must rememeber to increment i. i ++; } if (! found) { System.out.println ("String " + word + " not found"); } } }