如何使用Java中的`^`标志使用printf使文本居中? [英] How to center a text using printf with `^` flag in Java?

查看:576
本文介绍了如何使用Java中的`^`标志使用printf使文本居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以这样做:

  String s =Hello; 
int maxLength = 10;
System.out.print(getSpaces((maxLength - s.length())/ 2)+ s + getSpaces((maxLength - s.length())/ 2));

但我需要以一种简单的方式来完成。根据此页面: Printf for Java Specification 3.0 (第9章标志):

我可以使用 ^ 作为文本的中心 printf()这样的标志:

  String s =你好; 
int maxLength = 10;
System.out.printf(%^+ maxLength +s,s);

但是我得到这个错误:

<$ p











$ $ b

printf()

中使用 ^ 标志的正确方法是什么? b $ b

解决方案

格式化字符串语法,包括有关说明符和标志的信息可以在这里找到: java.util.Formatter



I don在本文档中的任何地方都可以使用 ^ 作为标志。



我相信你在链接中的规范以上不是标准Java,而是由 SharkySoft 生成的名为Lava3 Printf的第三方库。请让我们知道,如果这是你正在使用的图书馆,或者如果你正在尝试使用核心Java编码。


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()?

解决方案

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.

这篇关于如何使用Java中的`^`标志使用printf使文本居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆