2013-09-28 58 views
0

我试图读取文本文件(“puzzle.txt”)的某些行,并将它们保存到二维数组中作为wordsearch问题的一部分。第一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,所以我猜这个问题对于那些拥有更多经验的人来说是非常明显的。帮帮我?

回答

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])); 
} 
+0

就解决它,谢谢! :) –

0

您GOT补充:

s = sc.nextLine(); 

grid[i] = s.toCharArray(); 

Remeber前加入。摆脱内部循环。