Java如何格式化输出?

  在JavaSe5中,推出了C语言中printf()风格的格式化输出。这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力。今天,我们开始学习Java中的格式化输出。

System.out.format()

        由于内容比较简单,我们通过实例来加以说明。项目结构如下:

        Java Se5引入的format方法可用于PrintStream或PrintWriter对象,其中也包括System.out对象。

package com.tomhu.format;

public class FormatTest1 {

    public static void main(String[] args) {
        int x = 5;
        double y = 3.141592;

        // 一般方式
        System.out.println("x = " + x + ", y = " + y);
        // printf()方式
        System.out.printf("x = %d, y = %f\n", x, y);
        // format()方式
        System.out.format("x = %d, y = %f\n", x, y);
    }
}

        输出的结果如下:

x = 5, y = 3.141592
x = 5, y = 3.141592
x = 5, y = 3.141592

        可以看到,format与printf是等价的,它们只需要一个简单的格式化字符串,加上一串参数即可,每个参数对应一个格式修饰符。

public PrintStream printf(String format, Object ... args) {
    return format(format, args);
}

        在format的具体代码中,其实就是调用Formatter的format方法:formatter.format(Locale.getDefault(), format, args);

public PrintStream format(String format, Object ... args) {
    try {
        synchronized (this) {
            ensureOpen();
            if ((formatter == null)
  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值