我正在使用java,我想根据用户输入多次水平打印2d数组。但是,我的阵列垂直打印,有人可以帮忙吗?
n=3; //user input
char[][] board = new char[2][3];
char[][] f = new char[board.length][n * board[0].length];
for (int i = 1; i < n + 1; i++) {
int Start = (i * board[0].length) - board[0].length;
int End = i * board[0].length;
for (int row = 0; row < f.length; row++) {
for (int col = nStart; col < nEnd; col++) {
f[row][col] = board[row][col - nStart];
System.out.print(f[row][col]);
}
System.out.println();
}
}
For example board array =
xx
xx
I would like
xxxxxx
xxxxxx
答案 0 :(得分:1)
如果要水平打印2d数组,则必须在下一行之前重复打印行n
次:
int n = 3; // user input
char[][] board = new char[][] { { 'x', 'x', 'x' }, { '0', '0', '0' } }; //example board
for (int row = 0; row < board.length; row++)
{
for (int i = 0; i < n; i++)
{
for (int col = 0; col < board[row].length; col++)
{
System.out.print(board[row][col]);
}
System.out.print("\t"); //arrays separated by tab
}
System.out.println();
}
输出:
xxx xxx xxx
000 000 000
我希望这有帮助。
答案 1 :(得分:0)
您的解决方案工作正常,只是您在代码的最后几行中犯了一点错误。我想你想使用 System.out.println()在每个条目之间打印一个空格,但 println 会在最后打印一个换行符。所以你的代码应该是这样的:
n=3; //user input
char[][] board = new char[2][3];
char[][] f = new char[board.length][n * board[0].length];
for (int i = 1; i < n + 1; i++) {
int Start = (i * board[0].length) - board[0].length;
int End = i * board[0].length;
for (int row = 0; row < f.length; row++) {
for (int col = nStart; col < nEnd; col++) {
f[row][col] = board[row][col - nStart];
System.out.print(f[row][col]);
}
System.out.print(" "); // Print a space between every single output
}
}
或者,如果你不想要一个空间完全删除线。或者将空格更改为逗号,点或任何您需要的内容。
答案 2 :(得分:0)
删除复制的数组f。 你需要的是交换row,col in循环。
n=3; //user input
char[][] board = new char[2][3];
for (int j = 0; j < board[0].length; j++) {
for (int i = 0; i < n ; i++) {
System.out.print(board[i][j]);
System.out.print(" ");
}
System.out.println();
}