2015-10-05 128 views
-2

不管是什麼代碼片斷,我嘗試,其中我在網上找(大多是從堆棧交換/溢出),我無法弄清楚如何轉換(或「分配」)將一維數組的元素轉換爲二維數組。將Java一維數組爲二維數組

String str = in.next(); // Read the incoming text file and store it as a string 
char[] oneDcharArray = str.toCharArray(); // Convert the string into a 1D array 
maze = new char[numberOfRows][numberOfColumns]; // Assign row/column size to 2D array 
int count = 0; 

for (row = 0; row < numberOfRows; row++) 
{ 
    for (column = 0; column < numberOfColumns; column++) 
    { 
     // Convert 1D array into 2D array 
     maze[row][column] = oneDcharArray[count]; // Error: ArrayIndexOutOfBoundsException 
     count++; 
    } 
} 

下面Jags的回答很好,但它並不完美。它打印:

Row 0: ++++++++++ 
Row 1: S+++++++++ 
Row 2: ++++++++++ 
Row 3: +++++ 0000 0000 0000 0000 0000 
Row 0: ++++++++++ 
Row 1: OOOOOOOOOO 
...... 
+0

你怎麼能保證你有足夠的行容納一維數組項? – dave

+0

提示:使用調試器,並按照'count' VAR,看看它有多高去... –

+0

什麼是'numberOfRows','numberOfColumns',輸入字符串的值和長度? – Rehman

回答

0

//行×COL必須等於單d陣列

public static char[][] conversion(char[] array, int rows, int cols) 
    { 
     if (array.length != (rows*cols)) 
     throw new IllegalArgumentException("Invalid array length"); 
     char[][] array2d = new char[rows][cols]; 
     for (int i = 0; i < rows; i++) 
       System.arraycopy(array, (i*cols), array2d[i], 0, cols); 

       return array2d; 
    } 
+0

謝謝。我會嘗試。 –

+0

我寧願不使用其他方法。這對我的編程水平來說看起來有點複雜。抱歉。 –

0

下面的示例代碼應該工作。您需要循環訪問oneDcharArray,而不是行/列。但請注意,這一切都取決於您創建迷宮的要求。即您想如何將可用字符分爲N x M數組。

public class OneToTwo { 

    public static void main(String[] args) { 

     String str = "This is my test string with some words in it."; 
     char[] oneDcharArray = str.toCharArray(); // Convert the string into a 1D array 

     int numberOfColumns = 10; 
     int numberOfRows = (int)Math.ceil(oneDcharArray.length/numberOfColumns) + 1; // its not modulo 

     char[][] maze = new char[numberOfRows][numberOfColumns]; // Assign row/column size to 2D array 
     int count = 0; 

     int row =0 ,column = 0; 

     for (char c:oneDcharArray) { 

      if(column >= numberOfColumns) { 
       row++; 
       column = 0; 
      } 
      maze[row][column] = c; 
      column++; 
     } 

     //Test it 

     for (row = 0; row < numberOfRows; row++) { 
      System.out.print("Row "+row+": "); 
      for (column = 0; column < numberOfColumns; column++) { 
       // Convert 1D array into 2D array 
       System.out.print(maze[row][column]); 
       count++; 
      } 
      System.out.println(); 
     }  
    } 

} 

輸出

Row 0: This is my 
Row 1: test stri 
Row 2: ng with so 
Row 3: me words i 
Row 4: n it. 
+0

謝謝。我會嘗試。 –

+0

我編輯了我原來的帖子。請看底部。謝謝! –