我试图从文本文件(“puzzle.txt”)读取一些行,并将它们保存为二维数组,作为wordsearch问题的一部分。前十一行看起来像这样:
10 10
WVERTICALL
ROOAFFLSAB
ACRILIATOA
NDODKONWDC
DRKESOODDK
OEEPZEGLIW
MSIIHOAERA
ALRKRRIRER
KODIDEDRCD
HELWSLEUTH
前两个整数(R和C)是行数和列数,并且都正确读取。然而,其余部分无效。当我尝试将第2-10行打印为字符串时,我得到的是:
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
......等等。
import java.util.Scanner;
import java.util.Arrays;
import java.io.File;
public class WordSearch {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("puzzle.txt"));
/* Creating a 2D array of size R x C, variables in puzzle.txt
specifying the number of rows and the number of columns
respectively, and putting the next R lines of puzzle.txt into
that array. */
// Reading in variables R and C from puzzle.txt
int R = sc.nextInt();
int C = sc.nextInt();
// Initializing array of size R x C
char[][] grid = new char[R][C];
String s = sc.nextLine();
for (int i=0;i<R;i++) {
for (int j=0;j<C;j++) {
grid[j] = s.toCharArray();
System.out.print(Arrays.toString(grid[j]));
}
}
}
我是Java的新手,所以我猜这个问题对于那些有经验的人来说非常明显。帮助
答案 0 :(得分:0)
你必须补充:
s = sc.nextLine();
前
grid[i] = s.toCharArray();
记住之前添加它。摆脱内循环。
答案 1 :(得分:0)
尝试:
char[][] grid = new char[R][];
sc.nextLine(); // flush the line containing R and C
for (int i=0;i<R;i++) {
grid[i] = sc.nextLine().toCharArray(); // char array of size C
System.out.print(Arrays.toString(grid[i]));
}