我有一个.txt文件,我想把它转换成一个2d的字符数组。唯一的错误是linea.toCharArray();不能转换为2d数组
public static char[][] llegeixPuzle(String nomPuzle)throws IOException{
BufferedReader input = new BufferedReader(new FileReader(nomPuzle));
String linea = "";
char[][] 2dBoard = new char[0][0];
while((linea = input.readLine()) != null){
2dBoard = linea.toCharArray();
}
return 2dBoard;
}我的.txt文件包含以下内容
TCADRACT
PPPPPPPP
········
········
········
········
pppppppp
tcadract发布于 2021-03-14 00:45:40
首先,您必须计算您的rows和column,基本上您有8行8列。因此,首先我们创建了char [][]数组,以便保存数据
int totalRows = 8;
int totalColumn = 8;
char[][] myArray = new char[totalRows][totalColumn];创建我们将要读取的文件
File file = new File(nomPuzle);从try-catch构造开始,我们在每次迭代中遍历文件,然后创建一个新的char[] chars数组,然后遍历chars[]数组,然后将数据添加到数组myArray[i][j] = chars[j];中。
try(Scanner scanner = new Scanner(file)) { //try with resources
for (int i = 0; scanner.hasNextLine() && i < totalRows; i++) {
char[] chars = scanner.nextLine().toCharArray();
for (int j = 0; j < totalColumn && j < chars.length; j++) {
myArray[i][j] = chars[j];
}
}
}全码
public static void main(String[] args) throws IOException {
char [][] returnedArray = llegeixPuzle("YOURFILE.TXT");
System.out.println(Arrays.deepToString(returnedArray));
}
public static char[][] llegeixPuzle(String nomPuzle)throws IOException {
int totalRows = 8;
int totalColumn = 8;
char[][] myArray = new char[totalRows][totalColumn];
File file = new File(nomPuzle);
try(Scanner scanner = new Scanner(file)) { //try with resources
for (int i = 0; scanner.hasNextLine() && i < totalRows; i++) {
char[] chars = scanner.nextLine().toCharArray();
for (int j = 0; j < totalColumn && j < chars.length; j++) {
myArray[i][j] = chars[j];
}
}
}
return myArray;
}
}输出
[[T, C, A, D, R, A, C, T], [P, P, P, P, P, P, P, P], [·, ·, ·, ·, ·, ·, ·, ·], [·, ·, ·, ·, ·, ·, ·, ·], [·, ·, ·, ·, ·, ·, ·, ·], [·, ·, ·, ·, ·, ·, ·, ·], [p, p, p, p, p, p, p, p], [t, c, a, d, r, a, c, t]]https://stackoverflow.com/questions/66619782
复制相似问题