Search code examples
javastringmultidimensional-arraycharwordsearch

Best Way to Convert 1D String Array to a 2D Char Array in Java (Eclipse)


For a Word Search Game in Java, I am asking the user to enter as many words as they like (they will type a single 'q' if they want to stop adding more words), and this input is stored in an Array List, which is then converted to a 1D Array called words. I then call on a method in main to begin the game. Here is the code snippet:

System.out.println("Grid of the game");
for(char[] j : letterGrid) {
    System.out.println(j);
  }
   System.out.println("Search for these words...\n");
    for(String j : words) {
    	 System.out.print(j + ", ");
    }  
    System.out.print("Enter the Word: ");
    String word = br.readLine();
    System.out.print("Enter Row Number: ");
    int row = Integer.parseInt(br.readLine());
     //matching the word using regex
    Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
     Matcher matcher = pattern.matcher(letterGrid[row-1]);

letterGrid is a 2D char Array, but at the line where it says: Matcher matcher = pattern.matcher(letterGrid[row-1]); an error happens, and it says: The method matcher(CharSequence) in the type Pattern is not applicable for the arguments. I tried changing my program and turning letterGrid into a 1D String array, and it works fine for that, but not for a 2D char array. I fill letterGrid with random letters and the user words (horizontally, vertically, or diagonally. None backwards).

I am stuck on this and I am currently looking for ways get my problem fixed, but I figured I could ask here as well since people here provide good advice and suggestions. Any help will be appreciated!


Solution

  • the only acceptable argument to matcher is string & the quickest way to convert char to string is:

    char c = 'a';
    String s = String.valueOf(c);  
    

    so, you can do this:

    String s = String.valueOf(letterGrid[row-1]);
    Matcher matcher = pattern.matcher(s);