首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java printf格式用于打印表或列中的项

Java printf格式用于打印表或列中的项
EN

Stack Overflow用户
提问于 2015-11-01 19:55:50
回答 4查看 30.5K关注 0票数 4

我想用printf在整齐的列中打印东西。

代码语言:javascript
运行
复制
happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]

我有这段代码System.out.printf("%s %.6f %s \n", word, web.getFrequency(word), loc);,但它打印出来如下:

代码语言:javascript
运行
复制
happening  0.083333  [ 4 ] 
hi  0.083333  [ 0 ] 
if  0.083333  [ 8 ] 
important  0.083333  [ 7 ] 
is  0.250000  [ 3 5 10 ] 
it  0.166667  [ 6 9 ] 
tagged  0.083333  [ 11 ] 
there  0.083333  [ 1 ] 
what  0.083333  [ 2 ] 

任何帮助都将不胜感激。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-11-01 20:14:36

我会用这个:

代码语言:javascript
运行
复制
System.out.printf ("%-30s %1.7f %s%n", word, etc, etc2);
票数 9
EN

Stack Overflow用户

发布于 2015-11-01 20:17:45

您可以获得所有字串的最大长度,并将其存储在变量max中。使用一个for循环来获得那个max,然后创建一个具有格式的String,该格式将普通printf格式与要使用的max变量连接起来作为宽度。此外,\t还添加了一个制表符。

代码语言:javascript
运行
复制
int max = 0;
for (int ii = 0; ii < numberOfStrings; ii++)
{
   max = (word.length() > max) ? word.length() : max;
}
String format = "%" + max + "s\t%.6f\t%s \n";
System.out.printf(format, word, web.getFrequency(word), loc);
票数 1
EN

Stack Overflow用户

发布于 2016-10-08 00:50:19

代码语言:javascript
运行
复制
System.out.format("%-8s%-8s%-8s\n","a","b","pow(b,a)");
System.out.format("%-8d%-8d%-8d\n",1,2,1);
System.out.format("%-8d%-8d%-8d\n",2,3,8);
System.out.format("%-8d%-8d%-8d\n",3,4,81);
System.out.format("%-8d%-8d%-8d\n",4,5,1024);
System.out.format("%-8d%-8d%-8d\n",5,6,15625);

//the negative integer kinda sets it back to the number of space needed
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33466526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档