2015-06-01 64 views
0

將我正在從文件讀取的字符串轉換爲多維int數組,發現我認爲是建議here時,我遇到了一些麻煩。將字符串轉換爲多維int數組

對於字符串內容,請參閱此文件here

本質上我想替換CR和LF,以創建一個多維的int數組。

根據我的代碼,我可能會在哪裏出錯?

public static void fileRead(String fileContent) { 
    String[] items = fileContent.replaceAll("\\r", " ").replaceAll("\\n", " ").split(" "); 

    int[] results = new int[items.length]; 

    for (int i = 0; i < items.length; i++) { 
     try { 
      results[i] = Integer.parseInt(items[i]); 

      System.out.println(results[i]); 
     } catch (NumberFormatException nfe) {}; 
    } 
} 

編輯:我沒有遇到任何錯誤。上述邏輯只創建一個大小爲2的int數組,即結果[0] = 5和結果[1] = 5

感謝您的任何建議。

+0

你需要解釋一下你看到什麼清楚的錯誤。另外,你爲什麼要'replaceAll(「\\ r」,「」)'兩次?你是否認爲其中一個人是'\\ n'? – Nashenas

+0

你可以看看這個鏈接 - http://stackoverflow.com/questions/22185683/read-txt-file-into-2d-array – Razib

+0

@Nashenas:謝謝,但我沒有遇到任何錯誤。上述邏輯只創建一個大小爲2的int數組,即結果[0] = 5和結果[1] = 5 – ANM

回答

1

這裏的Java 8解決方案:

private static final Pattern WHITESPACE = Pattern.compile("\\s+"); 

public static int[][] convert(BufferedReader reader) { 
    return reader.lines() 
      .map(line -> WHITESPACE.splitAsStream(line) 
        .mapToInt(Integer::parseInt).toArray()) 
      .toArray(int[][]::new); 
} 

使用(當然你也可以從文件以及讀取):

int[][] array = convert(new BufferedReader(new StringReader("1 2 3\n4 5 6\n7 8 9"))); 
System.out.println(Arrays.deepToString(array)); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]