How to center a text using printf with `^` flag in Java?

主宰稳场 提交于 2019-12-11 06:42:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!