0

I need to display some matrices to view (java fx is used). I have string which contains matrices. The problem is that when I want to display it to view, the corresponding columns are not at the right place, for example

1 4 6
23 15 17
3 6 25

So as you can see, because numbers has different number of digits, it does not show correctly... Code for printing:

public static void printMatrix(double[][] matrix) {
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            String x = String.format("%5d ", (int) matrix[i][j]);
            Helper.matrixString += x;
        }
        Helper.matrixString += System.lineSeparator();
    }
}
Sirnius
  • 3
  • 2

2 Answers2

1

this should work (adds a " " padding in front of the number")

"% 5d" 

instead of (just adds a " " after the number);

"%5d "

Test code:

public static void main(String[] args) {
    double[][] matrix = {
            {1,4,6},
            {23,15,17},
            {3,5,25}
    };
    printMatrix(matrix);
}

public static void printMatrix(double[][] matrix) {
    for (int i = 0; i < matrix.length; i++) {
        String l = "";

        for (int j = 0; j < matrix[i].length; j++) {
            String x = String.format("%5d ", (int) matrix[i][j]);
            l += x;
        }
        System.out.println(l);
    }
}

output is

    1     4     6 
   23    15    17 
    3     5    25 

from http://grails.asia/convert-java-integer-to-fixed-length-string

JavaMan
  • 1,142
  • 12
  • 22
0

Method String.format uses the Formatter#syntax, where "%5d " - means formatting as a five-digit number with a leading spaces if necessary and one trailing space. In this case "%2d" is enough:

int[][] matrix = {
        {1, 4, 6},
        {23, 15, 17},
        {3, 6, 25}};
Arrays.stream(matrix)
        .map(row -> Arrays.stream(row)
                // formatting as a two-digit number
                // with a leading space if necessary
                .mapToObj(i -> String.format("%2d", i))
                // an array of strings representing
                // numbers in specified format
                .toArray(String[]::new))
        // string representation of rows
        .map(Arrays::toString)
        // output rows in a column
        .forEach(System.out::println);

Output:

[ 1,  4,  6]
[23, 15, 17]
[ 3,  6, 25]

See also:
How do I rotate a matrix 90 degrees counterclockwise in java?
Formatting 2d array of stings