How to print a 2d array horizontally multiple times

Viewed 2003

I am using java and I would like to print a 2d array horizontally multiple time based on user input. However, my array prints vertically, can anyone help?

    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
3 Answers

If you want to print 2d array horizontally, you have to repeat printing row n times before next row:

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();
}

Output:

xxx xxx xxx 
000 000 000 

I hope this help.

Your solution works fine except that you made a little mistake in the last lines of your code. I think you want to print a space between every entry by using System.out.println() but println prints a line-break at the end. So your code should look like this:

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
    }
}

Or if you dont wan't a space at all remove the line completely. Or change the space to a comma, point or whatever you need.

Removing the copied array f. What you need is exchanging row,col in loop.

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();
}
Related