java - 如何在java中使用printf()打印表格? [英] How do I use printf() in java to print out a table?

查看:58
本文介绍了java - 如何在java中使用printf()打印表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印一个表格,其中每一列都是一个不同的数组列表,然后每个元素在一行中.所以是这样的:

I'm trying to print out a table, in which each column is a different arraylist, where each element then goes down a line. So something like this:

Name:    Age:    Gender:
Bob        18      Male
Mary       25      Female

等等..我将如何使用 printf() 语句格式化它?

And so on.. How would I format this with the printf() statement?

推荐答案

首先看看 格式化字符串.String.formatprintf 共享相同的格式规则

Start by having a look at Formatted Strings. String.format and printf share the same formatting rules

所以,像……

System.out.printf("%15s", "Name:");
System.out.printf("%4s", "Age:");
System.out.printf("%17s:%n", "Gender:");

会产生类似...

Name:          Age:          Gender:

现在,我有意将示例分成三行,但您可以使用一行,例如 System.out.printf("%-15s%-4s%17s%n", "Name:", "Age:", "Gender:"); 代替.

Now, I've deliberatly broken down the example into three lines, but you could use a single line like System.out.printf("%-15s%-4s%17s%n", "Name:", "Age:", "Gender:"); instead.

这里重要的是%s之间的数字,%15s,它允许格式化程序用最多 15 个空格(对于 Name: 这将增加 10 个空格),这将在下一个示例中变得明显...

The important thing here is number between the % and s, %15s, which allows the formatter to fill out the remaining space with up to 15 spaces (for Name: that will add 10 more spaces), this will become obvious with the next example...

接下来我们需要对数据进行格式化,例如...

Next we need to format the data, for example...

String name = "Bob";
int age = 18;
String gender = "Male";
System.out.printf("%-15s", name);
System.out.printf("%4d", age);
System.out.printf("%17s%n", gender);

name = "Mary";
age = 25;
gender = "Female";
System.out.printf("%-15s", name);
System.out.printf("%4d", age);
System.out.printf("%17s%n", gender);

请注意,每列使用相同的间距!这很重要!

Note, that each column is using the same spacing! This is important!

总而言之,这将打印出来......

Altogether, this will print out...

Name:          Age:          Gender:
Bob              18             Male
Mary             25           Female

另见格式字符串语法 有关格式说明符的更多详细信息

Also see Format String Syntax for more details about the format specifers

这篇关于java - 如何在java中使用printf()打印表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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