2012-12-07 175 views
0

我有一個數組是從.split命令,並希望把它放入一個名爲String [] [] datatabvars的數組,我不知道如何將datatabarrs變成一個二維數組並將數據放入其中。multidimensional String [] [] array java

public String[] getList() { 
    String file_name = "path"; 
    String[] links = null; 
    String[][] datatabvars = null; // this var 
    int numberOfDatatabs = 0; 
    try { 
     ReadFile file = new ReadFile(file_name); 
     String[] aryLines = file.OpenFile(); 

      int i; 
     for(i=0; i < aryLines.length; i++) { //aryLines.length 
      if (aryLines[i].substring(0, 7).equals("datatab")) { 
       aryLines[i] = aryLines[i].replace("datatab["+Integer.toString(numberOfDatatabs)+"] = new Array(", ""); 
       aryLines[i] = aryLines[i].replace(");", ""); 
       datatabvars = aryLines[i].split(","); // this split array 
       numberOfDatatabs++; 
      } 
     } 
     System.out.println(datatabvars[0]); 
    }catch (IOException e) { 
     System.out.println(e.getMessage()); 
    } 
    return links; 
} 

回答

1

一般來說,陣列以避免瘟疫一樣 - 使用如果可能的話收集:在這種情況下,split()返回String[],所以使用,但使用List<String[]>存儲多個String[]

List<String[]> datatabvars = new ArrayList<String[]>(); 
... 
String[] array = input.split(","); 
datatabvars.add(array); 

你會發現生活是非常容易使用集合比數組。

3

更新兩行(我加評論)如下:(我假設你的代碼是其他工作)

String[][] datatabvars = null; // this var 
int numberOfDatatabs = 0; 
try { 
    ReadFile file = new ReadFile(file_name); 
    String[] aryLines = file.OpenFile(); 
    datatabvars = new String[aryLines.length][]; // INITIALIZED 

    int i; 
    for(i=0; i < aryLines.length; i++) { //aryLines.length 
     if (aryLines[i].substring(0, 7).equals("datatab")) { 
      aryLines[i] = aryLines[i]. 
         replace("datatab["+Integer.toString(numberOfDatatabs)+"] = 
               new Array(", ""); 
      aryLines[i] = aryLines[i].replace(");", ""); 
      datatabvars[i] = aryLines[i].split(","); // this split array: ASSIGNED 
      numberOfDatatabs++; 
     } 
    } 
    System.out.println(datatabvars[0]); 
+0

我試過使用datatabvars [numberOfDatatabs] = aryLines [i] .split(「,」); //這個分割不應該根據需要創建它們,從0開始,然後像Ti一樣高? – user1516251

+0

當你通過賦值給datatabvars [i]丟棄初始化長度爲10的數組時,你絕對不應該假定長度或初始化整個數組。相反,只要做datatabvars = new String [aryLines.length] [];初始化外部數組。其餘的代碼工作。 – tjltjl

+0

@ user1816548更新了答案。如果這是downvote的原因,請刪除。 –