java - 在 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。
我坚持这一点,我目前正在寻找解决问题的方法,但我想我也可以在这里提问,因为这里的人们提供了很好的建议和建议。任何帮助将不胜感激!
解决方案
matcher 唯一可接受的参数是字符串,将 char 转换为字符串的最快方法是:
char c = 'a';
String s = String.valueOf(c);
所以,你可以这样做:
String s = String.valueOf(letterGrid[row-1]);
Matcher matcher = pattern.matcher(s);
推荐阅读
- javascript - 为什么控制台会在我已经定义变量时记录我的变量未定义的错误?
- android - 即使在应用程序被杀死android之后,如何继续在前台启动的上传过程?
- reactjs - create-react-library 不适用于样式化组件
- c# - C# 是否支持自动返回 var 类型?
- c++ - 如何对 vtk Poly Data 进行布尔运算?
- highcharts - highcharts / node-export-server:包含大型数据集的空白图表
- ios - ios swift以编程方式根据所有iOS设备和方向显示图像?
- mysql - 为什么 EXPLAIN 根据 MySQL 中的用户返回不同的 Extra(文件排序)?
- javascript - sheetJS:当您想将毫秒转换为 h:mm 时,单元格对象应该如何显示?
- javascript - js应用程序中的cors策略阻止了FirebaseAuth请求