NewToThis NewToThis - 1 year ago 66
Java Question

Is it possible to set a column width for a Java output?

Good morning all, I am trying to work out the basics of Java and am trying to get a string to print with a specified column width in both the command line and console. Its a string of text so I don't want to truncate the data that doesn't fit, instead I want it to print on the next line if it doesn't fit within the specified width. Is this possible? I have looked at various things using formatter but have had no success.

Answer Source

It's not too difficult. You can do something like this:

public static void printLimit(Object obj, int width) {

    String val = obj.toString();

    if (val.length() > width && width > 0) {
        System.out.println(val.substring(0, width));
        printLimit(val.substring(width, val.length()), width);
    } else {