Java:将2D字符串数组打印为右对齐表 [英] Java: Print a 2D String array as a right-justified table

查看:225
本文介绍了Java:将2D字符串数组打印为右对齐表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打印 String [] [] 数组的单元格作为右对齐表的最佳方法是什么?例如,输入

  {{x,xxx},{yyy,y}, {zz,zz}} 

应该产生输出$ b $
pre $ $ $ $ $ $ $ $

这似乎是应该使用 java.util.Formatter 来完成的事情,但它似乎不允许非恒定的字段宽度。最好的答案是使用一些标准的方法来填充表格单元格,而不是手动插入空格字符。

解决方案

的确如果你为字段指定一个宽度,它应该是右对齐的。

如果你需要有一个动态的填充,最小的字符串最长,你必须走数组,获得最大宽度,生成格式字符串的宽度从这个最大值计算,并用它来格式化输出。

What is the best way to print the cells of a String[][] array as a right-justified table? For example, the input

{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } }

should yield the output

  x xxx
yyy   y
 zz  zz

This seems like something that one should be able to accomplish using java.util.Formatter, but it doesn't seem to allow non-constant field widths. The best answer will use some standard method for padding the table cells, not the manual insertion of space characters.

解决方案

Indeed, if you specify a width for the fields, it should be right-justified.
If you need to have a dynamic padding, minimal for the longest string, you have to walk the array, getting the maximal width, generate the format string with the width computed from this maxima, and use it for format the output.

这篇关于Java:将2D字符串数组打印为右对齐表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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