将Java 1D数组转换为2D数组

时间:2015-10-05 18:09:00

标签: java arrays 2d

无论我尝试哪些代码片段,我在互联网上找到的代码片段(主要来自Stack Exchange / Overflow),我都无法弄清楚如何转换(或“分配”)一维数组的元素成二维数组。

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
......

2 个答案:

答案 0 :(得分:0)

// rows * 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;
    }

答案 1 :(得分: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.