对于 Java 字符二维数组的输入,有以下三种方式:直接输入:使用char[][] grid = new charrowCount,然后逐个输入字符。从文件读取:使用Scanner读取文件中的字符,行列数需要提前确定。从字符串转换:使用split()和toCharArray()将字符串转换为字符数组。

Java 字符二维数组输入
直接输入
char[][] grid = new char[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
grid[i][j] = scanner.next().charAt(0);
}
}从文件读取
try (Scanner scanner = new Scanner(new File("input.txt"))) {
int rowCount = scanner.nextInt();
int columnCount = scanner.nextInt();
char[][] grid = new char[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
grid[i][j] = scanner.next().charAt(0);
}
}
} catch (FileNotFoundException e) {
// 处理找不到文件异常
}从字符串转换
String inputString = "a,b,c\nd,e,f";
char[][] grid = inputString.split("\n").stream()
.map(line -> line.split(","))
.map(line -> line[0].toCharArray())
.toArray(char[][]::new);注意点
-
rowCount 和 columnCount 需要提前确定。
- 如果输入字符不符合预期格式,可能导致异常。
- 对于大数组,文件读取方式可能会更有效率。
-
scanner.next().charAt(0) 将读取一个字符串的第一个字符。