How to align the elements of a matrix when printing it?

1

My question is how I could align the elements of an array so that they are aligned to the right.

This is the code I had done so far:

for (int i=0; i < matrix.length; i++)
    {  
        System.out.print("|");
        for (int j=0; j < matrix[i].length; j++)
        {
            System.out.print(" " + matrix[i][j] + " ");
        }
        System.out.print("|");
        System.out.println();
    }

Thanks for your response.

    
asked by Diego 16.12.2017 в 22:55
source

1 answer

3

The problem is that some numbers are 2 digits so you can undo the painting, for that you can use the method format of the class String in the following way:

 for (int i=0; i < matrix.length; i++)
            {  
                System.out.print("|");
                for (int j=0; j < matrix[i].length; j++)
                {
                    String value = String.format("%2s", matrix[i][j]);
                    System.out.print(" " + value + " ");
                }
                System.out.print("|");
                System.out.println();
            }

Keep in mind that "% 2s" tells you to show a string of up to 2 digits, so if your number is one digit, fill in the first digit with a blank.

The result is the following:

|  2   3  12 |
|  4   1   1 |
|  5  23   1 |
    
answered by 16.12.2017 / 23:15
source