java

How to indent in Java using format


I am looking to indent a print line in Java using format but I'm a little confused by the process.

I searched around and found this which presents the following option:

String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
 * The second string begins after 40 characters. The dash means that the
 * first string is left-justified.
 */
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);

I implemented it in my own code in the following way:

public class Main {

    public static void main(String[] args) {

        // Take in user input for report title
        System.out.println("Enter a title for this report");

        String msg = "=> ";
        String blank = "";

        String format = "%-4s%s%n";
        System.out.printf(format, blank, msg);
    }
}

I tried removing the blank with the following:

public class Main {

    public static void main(String[] args) {

        // Take in user input for report title
        System.out.println("Enter a title for this report");

        String msg = "=> ";

        String format = "%-4s%s%n";
        System.out.printf(format, msg);
    }
}

But I receive the following error in IntelliJ IDEA:

Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s' at java.base/java.util.Formatter.format(Formatter.java:2672) at java.base/java.io.PrintStream.format(PrintStream.java:1053) at java.base/java.io.PrintStream.printf(PrintStream.java:949) at Main.main(Main.java:32)

My question is, why is that first string required? Is there a way to do it without declaring the "blank" variable I have? I apologize if this is answered somewhere, I searched but could not find it.

This is my desired output:

Enter a title for this report
    =>

Solution

  • You just need to change your format string:

    String format = "%8s%n";
    

    Remove one %s as you are passing one less string compared to your example code and 8 is the indent for your second line.

    Use the value 8 because 1 tab = 8 spaces.