Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use print format to make box around text java?

Tags:

java

printf

public static void printBox(Scanner in, int length) {
    
    int spacesNeeded = 0;
    System.out.print("+"); 
    
    for (int i = 0; i <= length + 1; i++) {
        System.out.print("-");
    } 
    
    System.out.print("+");    
    System.out.println();
        
    while (in.hasNext()) {
        System.out.println("| " + in.nextLine() + " |");
    } 
    
    System.out.print("+");
    
    for (int i = 0; i <= length + 1; i++) {
        System.out.print("-");
    }
    
    System.out.print("+");    
    System.out.println();
    
}

Above code makes a box like this:

+--------------+
| This is some |
| text here. |
+--------------+

I need to find a better way to format this box and make the lines even with maybe a System.printf? or a better for loop process.

End products needs to be:

+--------------+
| This is some |
| text here.   |
+--------------+
like image 897
Lompang Avatar asked Jan 16 '15 05:01

Lompang


2 Answers

Let's start by writing a routine to get the maximum length of a number of String(s); something like

private static int getMaxLength(String... strings) {
    int len = Integer.MIN_VALUE;
    for (String str : strings) {
        len = Math.max(str.length(), len);
    }
    return len;
}

and methods to pad and and fill String(s). Padding can be done with something like

private static String padString(String str, int len) {
    StringBuilder sb = new StringBuilder(str);
    return sb.append(fill(' ', len - str.length())).toString();
}

Then you fill a String with len repeats of character ch(s) like

private static String fill(char ch, int len) {
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++) {
        sb.append(ch);
    }
    return sb.toString();
}

Finally, printBox is determining the length of the longest String. Building a top (and bottom line) then iterating the String(s) performing padding (if needed) on the String(s) and then using formatted output - | str | like

public static void printBox(String... strings) {
    int maxBoxWidth = getMaxLength(strings);
    String line = "+" + fill('-', maxBoxWidth + 2) + "+";
    System.out.println(line);
    for (String str : strings) {
        System.out.printf("| %s |%n", padString(str, maxBoxWidth));
    }
    System.out.println(line);
}

Then (for example)

public static void main(String[] args) {
    printBox("Thie is some", "text here.");
}

Output is

+--------------+
| Thie is some |
| text here.   |
+--------------+
like image 97
Elliott Frisch Avatar answered Oct 12 '22 23:10

Elliott Frisch


If you're certain the lines won't be too long, you can use this for your inner-most loop:

while (in.hasNext()) {
    String s = in.nextLine();
    int spaces = length - s.length();
    System.out.print("| " + s);
    while (spaces-- > 0)
        System.out.print(" ");
    System.out.println(" |");
}

This gives you output like:

+----------------------+
| hello there          |
| my name is pax       |
+----------------------+

for a length of 20 and a scanner providing those lines.

In that case, if the lines are longer than expected, you'll see something like:

+----------------------+
| hello there          |
| my name is pax       |
| This line is way too long |
+----------------------+

so, if that's possible, you may want to scan in all the lines up front (into a collection of some sort) keeping track of the maximum length as you go. Then use that length to decide how to print it out.

In other words, something like this, also refactoring out the code for the top and bottom edges since this is good practice:

public static void topBottom (int length) {
    System.out.print("+"); 
    for (int i = 0; i <= length + 1; i++)
        System.out.print("-");
    System.out.println("+");    
}

public static void printBox(Scanner in, int length) {
    ArrayList<String> lines = new ArrayList<String>();
    while (in.hasNext()) {
        String s = in.nextLine();
        if (s.length() > length)
            length = s.length();
        lines.add(s);
    }

    topBottom(length);
    for (String s: lines) {
        int spaces = length - s.length();
        System.out.print("| " + s);
        while (spaces-- > 0)
            System.out.print(" ");
        System.out.println(" |");
    }
    topBottom(length);
}

which adapts to the longest line:

+-------------------------------------------------------------+
| hello there                                                 |
| my name is pax                                              |
| and this is a very long line designed to test the functions |
+-------------------------------------------------------------+
like image 43
paxdiablo Avatar answered Oct 13 '22 01:10

paxdiablo