0

我试图从文本文件(“puzzle.txt”)中读取一些行并将它们保存到二维数组中,作为单词搜索问题的一部分。前 11 行如下所示:

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 新手,所以我猜这个问题对于那些有更多经验的人来说是非常明显的。帮助?

4

2 回答 2

0

你必须添加:

s = sc.nextLine();

grid[i] = s.toCharArray();

记得之前添加。摆脱内循环。

于 2013-09-28T17:46:10.180 回答
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]));
}
于 2013-09-28T17:47:36.697 回答