如何用Java打印信息表 [英] How to print a table of information in Java

查看:54
本文介绍了如何用Java打印信息表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Java打印表格,我想知道这样做的最佳方法是什么?

I'm trying to print a table in Java and I was wondering what is the best way to do this?

我尝试打印新行并使用\ t使内容对齐,但这不起作用.有没有一种方法可以做到这一点或更好的方法?

I've tried printing new lines and using \t to make contents line up but it doesn't work. Is there a method which does this or a better way?

推荐答案

您可以使用System.out.format(...)

You can use System.out.format(...)

示例:

final Object[][] table = new String[4][];
table[0] = new String[] { "foo", "bar", "baz" };
table[1] = new String[] { "bar2", "foo2", "baz2" };
table[2] = new String[] { "baz3", "bar3", "foo3" };
table[3] = new String[] { "foo4", "bar4", "baz4" };

for (final Object[] row : table) {
    System.out.format("%15s%15s%15s%n", row);
}

结果:

        foo            bar            baz
       bar2           foo2           baz2
       baz3           bar3           foo3
       foo4           bar4           baz4

或将以下代码用于左对齐输出:

Or use the following code for left-aligned output:

System.out.format("%-15s%-15s%-15s%n", row);

这篇关于如何用Java打印信息表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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