我正在开发一个程序,该程序要求我从文件中获取一维字符串数组并将其转换为二维数组。从文件中获取数组工作正常,但我无法让第二部分工作。
我正在使用的代码是:
char[][] array2 = new char [7][5];
for (int i = 0; i < array1.length; i++)
{
array2[i]= array[i].toCharArray();
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
{
System.out.println(array2[i][j]);
}
}
数组应该以网格格式打印,但向下打印。
感谢任何帮助,谢谢。
最佳答案
在内循环中使用print
而不是println
,并在每个循环之后使用println
打印一个空行。
for (int i = 0; i < 7; i++) // see changes 5/7. You did "new char[7][5]" not [5][7]
{
for (int j = 0; j < 5; j++) // see changes 7/5
{
System.out.print(array2[i][j]);
}
System.out.println();
}
更新:
以下是将字符串数组转换为二维字符数组的程序。
public class StringToChar {
public static void main(String[] args) {
String[] strArr = { "HELLO", "WORLD" };
char[][] char2D = new char[strArr.length][];
for (int i = 0; i < strArr.length; i++) {
char2D[i] = strArr[i].toCharArray();
}
for (char[] char1D : char2D) {
for (char c : char1D)
System.out.print(c + " ");
System.out.println();
}
}
}
关于java - 将一维字符串数组转换为二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19029943/