Home > database >  Is there a way to format numbers to have the same spacing between numbers?
Is there a way to format numbers to have the same spacing between numbers?

Time:06-23

So basically when some numbers are longer than others like 1 and 421 the spaces between them get bigger and doesn't look as clean in the final print... i would like to know is there is a better way of printing this matrix and putting those numbers in the same distance

//PRINT
String print1= " ";
for (int i=0;i<n;i  ){
    for (int j=0;j<n;j  ){
        print1 = magic[i][j];
        print1 ="               ";
    }
    print1  = "\n";
}
JOptionPane.showMessageDialog(null,print1);

Here it is how it looks:

screen capture

CodePudding user response:

In the below code, I use two ways to achieve your result. One way uses the stream API which was added in Java 8. The other way uses loops (similar to the code in your question). The code contains comments explaining what each part does. Note that I assign values to the 2D int array according to the image you linked to in your question. I also assume that you don't know the dimensions of the array nor the number of digits in the largest value in the array.

The key is static method format, in class java.lang.String. The first parameter to that method is a [format] String. I use the number of digits in the maximum value in the array. For the sample data this is 2 (two). Hence the format string is -. This means that each element in the array will be printed in a two-character string, padded with leading spaces if necessary, i.e. for single digit numbers the string will contain a single space followed by the digit and for two digit numbers the string will simply contain the two digits without leading spaces.

import java.util.Arrays;
import java.util.stream.Collectors;

public class MyData {

    /** Using loops. */
    private static void printLoop(int[][] magic) {

        // Find largest value in 'magic'.
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < magic.length; i  ) {
            for (int j = 0; j < magic[i].length; j  ) {
                if (magic[i][j] > max) {
                    max = magic[i][j];
                }
            }
        }

        // Get number of digits in 'max'.
        max = Integer.toString(max).length();

        // Convert each row in 'magic' to a string and print that string.
        for (int i = 0; i < magic.length; i  ) {
            boolean first = true;
            String row = "";
            for (int j : magic[i]) {
                if (first) {
                    first = false;
                }
                else {
                    row  = "               ";
                }
                row  = String.format("%"   max   "d", j);
            }
            System.out.println(row);
        }
    }

    /** Using stream API. */
    private static void printStream(int[][] magic) {

        // Find largest value in 'magic'.
        int max = Arrays.stream(magic) // creates Stream<int[]>
                        .flatMapToInt((int[] r) -> Arrays.stream(r)) // creates IntStream of all elements in 'magic'
                        .max() // Get maximum value in 'magic'
                        .orElseThrow(); // If 'max' not found, throw exception.

        // Get number of digits in 'max'.
        int digits = Integer.toString(max).length();

        // Convert each row in 'magic' to a string and print that string.
        Arrays.stream(magic) // creates Stream<int[]>
              .map((int[] r) -> Arrays.stream(r) // creates IntStream
                                      .mapToObj((int i) -> String.format("%"   digits   "d", i)) // Convert 'i' to [formatted] string
                                      .collect(Collectors.joining("               ", "", System.lineSeparator()))) // Concatenate all strings and append newline to resulting string
              .forEach(System.out::print); // Print each string created in previous step
    }

    public static void main(String[] args) {
        int[][] magic = new int[][]{{30, 39, 48, 1, 10, 19, 28},
                                    {38, 47, 7, 9, 18, 27, 29},
                                    {46, 6, 8, 17, 26, 35, 37},
                                    {5, 14, 16, 25, 34, 36, 45},
                                    {13, 15, 24, 33, 42, 44, 4},
                                    {21, 23, 32, 41, 43, 3, 12},
                                    {22, 31, 40, 49, 2, 11, 20}};
        printStream(magic);
        System.out.println("====================================================================");
        printLoop(magic);
    }
}

Regarding the following line from the above code:

.forEach(System.out::print); // Print each string created in previous step

The following part of that line is a method reference.

System.out::print

Here is the output I get:

30               39               48                1               10               19               28
38               47                7                9               18               27               29
46                6                8               17               26               35               37
 5               14               16               25               34               36               45
13               15               24               33               42               44                4
21               23               32               41               43                3               12
22               31               40               49                2               11               20
====================================================================
30               39               48                1               10               19               28
38               47                7                9               18               27               29
46                6                8               17               26               35               37
 5               14               16               25               34               36               45
13               15               24               33               42               44                4
21               23               32               41               43                3               12
22               31               40               49                2               11               20

CodePudding user response:

You can use Libraries like Apache common lang3's leftpad(..) method or can directly leverage String's format method, I have created method to return fixed length string (second param) here is your answer using String format

public static String fixedLengthString(String string, int length) {
    return String.format("%1$"   length   "s", string);
}
public static void print2DX(int[][] mat) {
    for (int i = 0; i < mat.length; i  ) {
        for (int j = 0; j < mat[i].length; j  ) {
            System.out.print(fixedLengthString(String.valueOf(mat[i][j]), 8)   " ");
        }
        System.out.println();
    }
}

CodePudding user response:

the best would be to get the number value and convert it to string and get it's length. lets take 354 as eg. So, length = 3. lets say your column length llimit is 8. So, the spacing you need to give is of 8-3(limit-length) which is 5(use a for loop to append the spaces or a switch case. that way, the string finally being attached is 354. with 5 spaces. different numbers will have different length. but, column size will be the same. So replace this-

print1 ="               ";

with a for loop which appends a space for remaining length. i.e. 5 as discussed above.

  •  Tags:  
  • java
  • Related