问题
I know I can do it as follows:
String s = "Hello";
int maxLength = 10;
System.out.print(getSpaces((maxLength - s.length()) / 2) + s + getSpaces((maxLength - s.length()) / 2));
But I need to do it in a simple way. According to this page: Printf for Java Specification 3.0 (Section 9. flags):
I can center the text using ^
as a flag with printf()
like this:
String s = "Hello";
int maxLength = 10;
System.out.printf("%^" + maxLength + "s", s);
But I got this error:
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '^'
What is the correct way to use ^
flag with printf()
?
回答1:
The format String syntax, including information on specifiers and flags can be found here: java.util.Formatter.
I don't see use of ^
as a flag anywhere in this documentation.
I believe that your specification in the link above isn't for standard Java but rather for a 3rd party library called Lava3 Printf produced by SharkySoft. Please let us know if this is the library you are using, or if you're trying to do this coding with core Java.
来源:https://stackoverflow.com/questions/8468467/how-to-center-a-text-using-printf-with-flag-in-java