2016-11-26 130 views
0

所以我有這樣的代碼:鏈接列表中的多維數組無法正常工作?

public static void main (String[] args) throws IOException 
{ 
    Queue popcorn = new LinkedList(); 
    BufferedReader in = null; 
    int j = 0; 
    try { 
     File file2 = new File("Events.txt"); 
     in = new BufferedReader(new FileReader(file2)); 

     String str; 
     String [][] process = new String[][]; 
     while ((str = in.readLine()) != null) { 
      String[] arr = str.split(" "); 
      for(int i=0 ; i<str.length() ; i++){ 
      process[j][i] = in.readLine(); 
     } 
      j++; 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

它不工作。它拋出「變量必須提供尺寸表達式或數組初始化 」

我想這個答案的網頁後,其建模「http://www.chegg.com/homework-help/questions-and-answers/hired-biggy-s-popcorn-handle-popcorn-orders-store-write-java-console-application-reads-dat-q7220573」 這我敢肯定是行不通的。無論如何,這個鏈表似乎沒有解決。就我的String [] []過程聲明而言,有人能指出我正確的方向嗎?

+0

'新的String [] []' - 這是不可能的* *創建無維數組,這是信息說什麼。這與變量聲明是分開的。搜索關於一般提示/方向的錯誤消息。 – user2864740

+0

您需要提供數組大小。閱讀http://www.java67.com/2014/10/how-to-create-and-initialize-two-dimensional-array-java-example.html – Rohan

回答

3

你不能只是初始化一個沒有維度參數的數組。例如,這是無效的:

int[] array = new int[]; 

它需要像這樣進行初始化:

int[] array = new int[10]; 

或者乾脆:

int[] array; 
// ... // 
array = new int[10]; 

這是一個與多維數組同樣的事情。爲了使含5號的3個數組的數組,你會放:

int[][] array = new int[3][5]; 

然而,隨着二維數組,你也可以把:

int[][] array = new int[3][]; 
array[0] = new int[5]; 
array[1] = new int[7]; 
// ... // 

的一點是,你需要定義多少其他數組將在您的基本數組中,並且還可以選擇定義所有數組的大小或稍後添加它們。在這種情況下,你需要改變

String [][] process = new String[][]; 

喜歡的東西

String [][] process = new String[x][y]; 
+0

好吧!所以我會用String [] [] process = new String [15] [];對不對? – user7212219

+0

是的,但請記住,如果您要使用'process [j] [i] = in.readLine();'行,您可能需要使用其他數組填充基本數組通過設置'process [j] = arr;'。 –