Reputation: 930
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
=>
Upvotes: 3
Views: 10246
Reputation: 9537
Multiline version for Java < 12:
public static String indent(String text, int indent) {
// Java 11: `var whitespace = " ".repeat(indent);`
var whitespace = String.format("%" + indent + "s", " ");
return whitespace + text.replaceAll("\\R", "\n" + whitespace);
}
For Java 12+, just use the indent function.
Upvotes: 0
Reputation: 1964
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
.
Upvotes: 3
Reputation: 2493
This may work.
import java.util.Formatter;
public class Main {
public static void main(String[] args) {
System.out.println("Enter a title for this report");
String msg = "=>";
String output = String.format("%6s\n",msg); //7 th line
System.out.print(output);
}
}
In the 7th line I have specified (6s) means total string will be of length 6. msg is length of 2 then remaining 4 spaces will be assigned to left(if we mention "-6" 4spaces will be assigned to right) to the string msg
Upvotes: 1