嗨,所以我应该从文本文件中读取行,然后输出 数据进入2D数组,我已经读过这些行,但是我很困惑 如何将内容输入2D数组。
这是文件:
eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply
wnarmupnke
ngrelclene
alytueyuei
fgrammarib
tdcebykxka
我的问题是如何将这些字符串放入2d数组中,如下所示。
public class WordFinder {
public static final int N = 10;
public static char[][] grid = new char[N][N];
public static final String GRID_FILE = "grid.txt";
public static void initGrid() {
try {
File file = new File(GRID_FILE);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
对于JAVA来说我还很陌生,所以任何帮助都将是我们不二之选!
答案 0 :(得分:0)
这里是对代码的快速修改,以使其正常工作。将一行读取为字符串,然后遍历字符串中的字符,并将其放置在Array.new(n, [])
数组中。
char[][]
输出:
import java.util.*;
import java.io.*;
public class WordFinder {
public static final int N = 10;
public static char[][] grid = new char[N][N];
public static final String GRID_FILE = "grid.txt";
public static void initGrid() {
try {
File file = new File(GRID_FILE);
Scanner scanner = new Scanner(file);
for (int i = 0; scanner.hasNext(); i++) {
String line = scanner.next();
for (int j = 0; j < N; j++) {
grid[i][j] = line.charAt(j);
}
}
scanner.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
public static void main(String[] args) {
initGrid();
for (char[] row : grid) {
for (char cell : row) {
System.out.print(cell);
}
System.out.println();
}
}
}
但是要小心:此设计可能会在10x10字符网格以外的输入文件上崩溃。考虑使用ArrayList动态匹配文本文件的大小,或者至少可以添加到错误处理中:
eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply
wnarmupnke
ngrelclene
alytueyuei
fgrammarib
tdcebykxka