不管是什麼代碼片斷,我嘗試,其中我在網上找(大多是從堆棧交換/溢出),我無法弄清楚如何轉換(或「分配」)將一維數組的元素轉換爲二維數組。將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
......
你怎麼能保證你有足夠的行容納一維數組項? – dave
提示:使用調試器,並按照'count' VAR,看看它有多高去... –
什麼是'numberOfRows','numberOfColumns',輸入字符串的值和長度? – Rehman