Java 2d 字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19054209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 2d char array
提问by user2817804
Good day everyone, for the past couple of days I have been working on converting a 1D string array to a 2D char array. My 1D array works fine(zero issues) but when I convert to the 2D char array it only prints out the first row. Below is my code. Any feedback is appreciated. Thanks!
大家好,在过去的几天里,我一直致力于将一维字符串数组转换为二维字符数组。我的一维数组工作正常(零问题)但是当我转换为二维字符数组时,它只打印出第一行。下面是我的代码。任何反馈表示赞赏。谢谢!
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();
}
回答by Bucket
You cannot have variables start with a number in Java. I suggest changing your variables accordingly and trying it out.
在 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();
}
回答by Bucket
See Comments
看评论
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();
}