2013-09-28 54 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前加入。擺脫內部循環。