首页 > 解决方案 > 在 Java (Eclipse) 中将一维字符串数组转换为二维字符数组的最佳方法

问题描述

对于 Java 中的单词搜索游戏,我要求用户输入任意数量的单词(如果他们想停止添加更多单词,他们将键入一个 'q'),并且此输入存储在一个数组列表中,然后将其转换为一个名为words.I 的一维数组,然后调用 main 中的一个方法来开始游戏。这是代码片段:

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 是一个 2D 字符数组,但在它说:Matcher matcher = pattern.matcher(letterGrid[row-1]);发生错误的那一行,它说:The method matcher(CharSequence) in the type Pattern is not applicable for the arguments.我尝试更改我的程序并将 letterGrid 转换为 1D 字符串数组,它可以正常工作,但不适用于 2D 字符大批。我用随机字母和用户词(水平、垂直或对角线。没有向后)填充 letterGrid。

我坚持这一点,我目前正在寻找解决问题的方法,但我想我也可以在这里提问,因为这里的人们提供了很好的建议和建议。任何帮助将不胜感激!

标签: javastringmultidimensional-arraycharwordsearch

解决方案


matcher 唯一可接受的参数是字符串,将 char 转换为字符串的最快方法是:

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

所以,你可以这样做:

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

推荐阅读