如何使用printf()和可变宽度居中输出字符串? 【JAVA] [英] How to center string output using printf() and variable width? [java]

查看:590
本文介绍了如何使用printf()和可变宽度居中输出字符串? 【JAVA]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用printf()在Java中创建输出来创建表头。其中一列需要可变宽度。

I'm creating an output in Java using printf() to create table headers. One of the columns needs variable width.

基本上它应该是这样的:

Basically it should look like this:

//two coords
Trial    Column Heading
1        (20,30)(30,20)
//three coords
Trial        Column Heading
1        (20,40)(50,10)(90,30)

我试图使用:

int spacing = numCoords * 7; //size of column
printf("Trial    %*^s", column, "Column Heading");

但是当我尝试在转换语句中使用*或^时,我一直收到输出错误。

But I keep getting output errors when I try to use * or ^ in the conversion statement.

有没有人知道正确的格式字符串应该是什么?

Does anyone have any idea what the correct formatting string should be?

推荐答案

使用 Commons Lang图书馆中的StringUtils.center:

Use StringUtils.center from the Commons Lang library:

StringUtils.center(column, "Column Heading".length());

这篇关于如何使用printf()和可变宽度居中输出字符串? 【JAVA]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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