Properly indent Java/Kotlin console output

1.3k views Asked by At

I am outputting a lot of information to the console that is gathered across multiple nested calls. I would like to be able to print the information on the screen in a readable manner but the I can't seem to get the indentation right, without hardcoding the number the number of \ts.

Basically, how can I get my code to indent based on the indentation level of the previous line. If the previous line is indented with \t and I do "\n\t", after that, I would like the new line to indent with respect to the previous line. Meaning I expected to be like

String str = "original line (no indention)"
+ "\n"
+ "\t originally indented line"
+ "\n"
+ "\t the second indented line"

The output is

original line (no indention)
    originally indented line
    the second indented line

but I would like it to be

original line (no indention)
    originally indented line
         the second indented line

Please keep in mind that in my actual code each level of indention is a result of aggregation from a different file so it's hard to just know to indent twice on the second line. I need it to be able to indent simply based on the indentation of previous line so I don't have to hard code the levels of indentation.

2

There are 2 answers

0
jadeblack12 On BEST ANSWER

Ended up, replacing every new line \n with \n\t during each iteration and that seemed to do the trick. Crazy how it was such a simple solution that I over looked.

0
jbinvnt On

I would recommend creating a mini class to help you with this. That way you can keep track of how many indents have already been made. You can add the following code inside the class you're currently using:

public static class Indent{
    private static int numIndents = 0;
    public static String addIndent(String textToIndent){
        numIndents++;
        for(int i = 0; i < numIndents; i++){
            textToIndent = "\t" + textToIndent;
        }
        return textToIndent;
    }
}

Then you can do the following:

String str = "original line (no indention)"
+ Indent.addIndent("originally indented line") 
+ Indent.addIndent("second indented line");

And that way you actually never have to type \t at all.