2013-11-22 18 views
0

我正在使用多維數組,但我卡住了。 第一行是測試用例的數量,下一行讀取int(N)並構造N * N grid。我只需要一些測試用例的幫助。 我已經做了以下的東西......InputReader格式化

 public static int[][] parseInput(final String fileName) throws Exception { 
      BufferedReader reader = new BufferedReader(new FileReader(fileName)); 

      int n = Integer.parseInt(reader.readLine()); 
      int[][] result = new int[n][n]; 

      String line; 
      int i = 0; 
      while ((line = reader.readLine()) != null) { 
       String[] tokens = line.split(""); 
       for (int j = 0; j < n; j++) { 
        result[i][j] = Integer.parseInt(tokens[j]); 
     } 

      i++; 
     } 

     return result; 
    } 

剛需如何解讀這個樣本輸入

3 
2 
|| 
.. 
3 
|.| 
... 
||| 
2 
|. 
.| 

如何在第一線讀出,以便繼續閱讀餘下的測試用例。上面的例子(讀入3並讀入3個輸入來構建網格)。

+2

什麼問題? –

+0

另外,請正確縮進您的代碼。 – Keppil

+0

編輯@Keppil,謝謝。 – saopayne

回答

0

嘗試使用這個(我認爲這是一個編程競賽問題) 這個例子在標準輸入讀取。您可以使用FileReader(您的閱讀器)代替。其他人是一樣的。

public class Test { 

public static void main(String[] args) throws Exception { 
    solve(); 
} 

public static void solve() throws Exception { 

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 
    int testcases = Integer.parseInt(reader.readLine()); 

    int i = 0; 
    for (i = 0; i < testcases; ++i) { 
     int n = Integer.parseInt(reader.readLine()); 
     int[][] result ; 

     result = parseInput(reader, n); 

     System.out.println("####"); 
     for(int j=0;j<n;++j){ 
      for(int k=0;k<n;++k){ 
       System.out.print(result[j][k] + " "); 
      } 
      System.out.println(); 
     } 
     System.out.println("####"); 
    } 
} 

public static int[][] parseInput(BufferedReader reader, int n) throws Exception { 

    int[][] result = new int[n][n]; 

    String line; 
    int i = 0; 
    for (i = 0; i < n; ++i) { 
     line = reader.readLine(); 
     for (int j = 0; j < n; j++) { 
      result[i][j] = line.charAt(j); 
     } 
    } 

    return result; 
} 
} 
0

請試試這個:

public static void parseInput(final String fileName) throws Exception { 
    BufferedReader reader = new BufferedReader(new FileReader(fileName)); 

    int test_cnt = Integer.parseInt(reader.readLine()); 
    for(int i = 0; i < test_cnt;i++){ 
     int n = Integer.parseInt(reader.readLine()); 
     int[][] grid = parseInput(n, reader); 
     //do something for result grid 
    } 
} 

private static int[][] parseInput(int n, BufferedReader reader) throws Exception{ 
    int[][] result = new int[n][n]; 
    String line; 
    int i = 0; 
    while (i < n && (line = reader.readLine()) != null) { 
     //String[] tokens = line.split(""); 
     char[] tokens = line.toCharArray(); 
     for (int j = 0; j < n; j++) { 
      result[i][j] = (int)tokens[j]; 
     } 
     i++; 
    } 
    return result; 
} 
+0

請注意。我想「|」要麼 」。」作爲一些整數,因爲你聲明「int [] []結果」。 – toshi