2

大家好,在过去的几天里,我一直致力于将一维字符串数组转换为二维字符数组。我的一维数组工作正常(零问题),但是当我转换为二维字符数组时,它只打印出第一行。下面是我的代码。任何反馈表示赞赏。谢谢!

for(int i = 0; i < array1.length; i++) //prints out array
{  
    System.out.println("1d " + number[i]); //prints the line from the file
}
final int ROWS = 7;
final int COLS = 5;

char[][] 2darray = new char [ROWS][COLS];

for (int i = 0; i < array.length; i++)
{
    2darray[i]= array1[i].toCharArray();   
}

for (int row = 0; row < ROWS; row++)
{
    for (int col = 0; col < COLS; col++)
    {
         System.out.print(2darray[row][col]);
    }
    System.out.println();
}
4

2 回答 2

3

在 Java 中,变量不能以数字开头。我建议相应地更改您的变量并尝试一下。

char[][] array2 = new char [ROWS][COLS];

for (int i = 0; i < array.length(); i++)
{
    array2[i]= array1[i].toCharArray();   
}

for (int row = 0; row < ROWS; row++)
{
    for (int col = 0; col < COLS; col++)
    {
         System.out.print(array2[row][col]);
    }
    System.out.println();
}
于 2013-09-27T15:17:09.420 回答
1

看评论

for(int i = 0; i < array1.length; i++) //prints out array
{  
    // Why did you use number ?
    System.out.println("1d " + array1[i]); //prints the line from the file
}

// You don't need these now.
// final int ROWS = 7;
//  final int COLS = 5;


// This will initialize 2darray of size as required according to length of array1
char[][] 2darray = new char [array1.length][];

for (int i = 0; i < array1.length; i++) // What is `array`?
{
    2darray[i]= array1[i].toCharArray();   
}

for (int row = 0; row < 2darray.length; row++) // Use actual size of 2darray row
{
    for (int col = 0; col < 2darray[i].length; col++) // use actual size of 2darray column
    { 
         System.out.print(2darray[row][col]);
    }
    System.out.println();
}
于 2013-09-27T15:30:53.597 回答