Java Printf 函数及其使用

Java Printf 函数及其使用

  System.out.printf() 是在JDK1.5版引入的方法,printf 方法有 printf(String format, Object ... args) 和 printf(Locale l, String format, Object ... args) 两种重载方式。

 printf 方法的代码解析

  printf(String format, Object ... args)  方法的代码

    /**
     * A convenience method to write a formatted string to this output stream
     * using the specified format string and arguments.
     *
     * <p> An invocation of this method of the form <tt>out.printf(format,
     * args)</tt> behaves in exactly the same way as the invocation
     *
     * <pre>
     *     out.format(format, args) </pre>
     *
     * @param  format
     *         A format string as described in <a
     *         href="../util/Formatter.html#syntax">Format string syntax</a>
     *    * @param  args
     *         Arguments referenced by the format specifiers in the format
     *         string.  If there are more arguments than format specifiers, the
     *         extra arguments are ignored.  The number of arguments is
     *         variable and may be zero.  The maximum number of arguments is
     *         limited by the maximum dimension of a Java array as defined by
     *         <cite>The Java™ Virtual Machine Specification</cite>.
     *         The behaviour on a
     *         <tt>null</tt> argument depends on the <a
     *         href="../util/Formatter.html#syntax">conversion</a>.
     *    * @throws  java.util.IllegalFormatException
     *          If a format string contains an illegal syntax, a format
     *          specifier that is incompatible with the given arguments,
     *          insufficient arguments given the format string, or other
     *          illegal conditions.  For specification of all possible
     *          formatting errors, see the <a
     *          href="../util/Formatter.html#detail">Details</a> section of the
     *          formatter class specification.
     *
     * @throws  NullPointerException
     *          If the <tt>format</tt> is <tt>null</tt>
     *
     * @return  This output stream
     *
     * @since  1.5
     */
    public PrintStream printf(String format, Object ... args) {
        return format(format, args);
    }
    public PrintStream format(String format, Object ... args) {
        try {
            synchronized (this) {
                ensureOpen();
                if ((formatter == null)
                    || (formatter.locale() != Locale.getDefault()))
                    formatter = new Formatter((Appendable) this);
                <span style="background-color: rgb(51, 255, 51);">formatter.format(Locale.getDefault(), format, args);</span>
            }
        } catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        } catch (IOException x) {
            trouble = true;
        }
        return this;
    }


  printf(Locale l, String format, Object ... args) 方法的代码

     /**
     * A convenience method to write a formatted string to this output stream
     * using the specified format string and arguments.
     *
     * <p> An invocation of this method of the form <tt>out.printf(l, format,
     * args)</tt> behaves in exactly the same way as the invocation
     *
     * <pre>
     *     out.format(l, format, args) </pre>
     *
     * @param  l
     *         The <a target=_blank href="mailto:{@linkplain">{@linkplain</a> java.util.Locale locale} to apply during
     *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
     *         is applied.
     *
     * @param  format
     *         A format string as described in <a
     *         href="../util/Formatter.html#syntax">Format string syntax</a>
     *
     * @param  args
     *         Arguments referenced by the format specifiers in the format
     *         string.  If there are more arguments than format specifiers, the
     *         extra arguments are ignored.  The number of arguments is
     *         variable and may be zero.  The maximum number of arguments is
     *         limited by the maximum dimension of a Java array as defined by
     *         <cite>The Java&trade; Virtual Machine Specification</cite>.
     *         The behaviour on a
     *         <tt>null</tt> argument depends on the <a
     *         href="../util/Formatter.html#syntax">conversion</a>.
     *
     * @throws  java.util.IllegalFormatException
     *          If a format string contains an illegal syntax, a format
     *          specifier that is incompatible with the given arguments,
     *          insufficient arguments given the format string, or other
     *          illegal conditions.  For specification of all possible
     *          formatting errors, see the <a
     *          href="../util/Formatter.html#detail">Details</a> section of the
     *          formatter class specification.
     *
     * @throws  NullPointerException
     *          If the <tt>format</tt> is <tt>null</tt>
     *
     * @return  This output stream
     *
     * @since  1.5
     */
    public PrintStream printf(Locale l, String format, Object ... args) {
        return format(l, format, args);
    }
    public PrintStream format(Locale l, String format, Object ... args) {
        try {
            synchronized (this) {
                ensureOpen();
                if ((formatter == null)
                    || (formatter.locale() != l))
                    formatter = new Formatter(this, l);
                <span style="background-color: rgb(51, 255, 51);">formatter.format(l, format, args);</span>
            }
        } catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        } catch (IOException x) {
            trouble = true;
        }
        return this;
    }

  

  从以上的两个重载代码可以看出,printf(String format, Object ... args)  就是基于Java环境的打印格式化方法实现,printf(Locale l, String format, Object ... args) 只是多了指定环境的适应的打印操作。


 printf 方法的使用

  

转换参数类别说明
'b', 'B'常规如果参数 argnull,则结果为 "false"。如果 arg 是一个 boolean 值或 Boolean,则结果为String.valueOf() 返回的字符串。否则结果为 "true"。
'h', 'H'常规如果参数 argnull,则结果为 "null"。否则,结果为调用 Integer.toHexString(arg.hashCode()) 得到的结果。
's', 'S'常规如果参数 argnull,则结果为 "null"。如果 arg 实现 Formattable,则调用 arg.formatTo。否则,结果为调用arg.toString() 得到的结果。
'c', 'C'字符结果是一个 Unicode 字符,可用于byte、short、char、Byte、Short、Character、Integer,‘%c’表示字母输出以小写表示,‘%C’则表示以大写表示
'd'整数结果被格式化为十进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger
'o'整数结果被格式化为八进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger
'x', 'X'整数结果被格式化为十六进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger,‘%x’表示字母输出以小写表示,‘%X’则表示以大写表示
'e', 'E'浮点结果被格式化为用计算机科学记数法表示的十进制数,可用于float、double、Float、Double、BigDecimal,‘%e’表示字母输出以小写表示,‘%E’则表示以大写表示
'f'浮点结果被格式化为十进制浮点数,可用于float、double、Float、Double、BigDecimal
'g', 'G'浮点根据精度和舍入运算后的值,使用计算机科学记数形式或十进制格式对结果进行格式化。
'a', 'A'浮点结果被格式化为带有效位数和指数的十六进制浮点数
't', 'T'日期/时间日期和时间转换字符的前缀。
'%'百分比结果为字面值 '%' ('\u0025')
'n'行分隔符结果为特定于平台的行分隔符,Windows 平台会切换为“\r\n”,Linux 会切换为“\n”,Mac OS 则切换为“\r”

  以上的转换参数需要在前面加入“ %”使用,如需要输出%,则要格式化为 “%%”
  
  

  示例代码:
    package cn.lwz.javase.test;

    import java.math.BigDecimal;
    import java.math.BigInteger;

    import org.junit.Test;
    /**
     * Printf 方法测试类
     * @author LiWenZhang
     * @date 2015-08-01
     */
    public class TestPrintf {
	@Test
	public void testPrintf() throws Exception {
		printBool();
		printHash();
		printStr();
		printChar();
		printInt();
		printOct();
		printHex();
		printExp();
		printFlo();
	}

	/**
	 * 'f' 浮点 结果被格式化为十进制浮点数,可用于float、double、Float、Double、BigDecimal
	 */
	private void printFlo() {
		printf(getFormat("f"), 100000000f, 200000000d, 300000000F, 400000000D, BigDecimal.valueOf(0x7fffffffffffffffL));
	}

	/**
	 * 'e', 'E' 浮点 结果被格式化为用计算机科学记数法表示的十进制数。
	 * 可用于float、double、Float、Double、BigDecimal,‘%e’表示字母输出以小写表示,‘%E’则表示以大写表示
	 */
	private void printExp() {
		printf(getFormat("e") + ", " + getFormat("E"), 100000000f, 200000000d, 300000000F, 400000000D,
				BigDecimal.valueOf(0x7fffffffffffffffL));
	}

	/**
	 * 'x', 'X' 整数 结果被格式化为十六进制整数。
	 * 可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger,
	 * ‘%x’表示字母输出以小写表示,‘%X’则表示以大写表示
	 */
	private void printHex() {
		printf(getFormat("x") + ", " + getFormat("X"), (byte) 100, (short) 200, 0,
				BigInteger.valueOf(0x7fffffffffffffffL));
	}

	/**
	 * 'o' 整数
	 * 结果被格式化为八进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger
	 */
	private void printOct() {
		printf(getFormat("o"), (byte) 100, (short) 200, 0, BigInteger.valueOf(0x7fffffffffffffffL));
	}

	/**
	 * 'b', 'B' 常规 如果参数 arg 为 null,则结果为 "false"。 如果 arg 是一个 boolean 值或
	 * Boolean,则结果为String.valueOf() 返回的字符串。否则结果为 "true"。
	 */
	private void printBool() {
		printf(getFormat("b") + ", " + getFormat("B"), true, false, "true", "false", 0, 'A');
	}

	/**
	 * 'h', 'H' 常规 如果参数 arg 为 null,则结果为 "null"。 否则,结果为调用
	 * Integer.toHexString(arg.hashCode()) 得到的结果。
	 */
	private void printHash() {
		printf(getFormat("h") + ", " + getFormat("H"), true, false, "true", 0, 'A');
	}

	/**
	 * 's', 'S' 常规 如果参数 arg 为 null,则结果为 "null"。 如果 arg 实现 Formattable,则调用
	 * arg.formatTo。否则,结果为调用arg.toString() 得到的结果。
	 */
	private void printStr() {
		printf(getFormat("s") + ", " + getFormat("S"), true, false, "true", 0, 'A');
	}

	/**
	 * 'c', 'C' 字符 结果是一个 Unicode 字符。
	 * 可用于byte、short、char、Byte、Short、Character、Integer,
	 * ‘%c’表示字母输出以小写表示,‘%C’则表示以大写表示
	 */
	private void printChar() {
		printf(getFormat("c") + ", " + getFormat("C"), (byte) 65, 97, 'A');
	}

	/**
	 * 'd' 整数
	 * 结果被格式化为十进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger
	 */
	private void printInt() {
		printf(getFormat("d"), (byte) 65, 97, BigInteger.valueOf(0x7fffffffffffffffL));
	}

	private void printf(String formatStr, Object... args) {
		Util.printMethodName();
		if (args != null && args.length > 0) {
			for (Object arg : args) {
				System.out.printf("param:" + arg + Util.getBlanks(arg, 25));
				System.out.printf(formatStr + "\n", arg, arg);
			}
		}
	}

	private String getFormat(String f) {
		return "Format: %%" + f + " >> %" + f;
	}
    }
    结果输出:
    
---------------------------------- printBool() ----------------------------------
param:true                     Format: %b >> true, Format: %B >> TRUE
param:false                    Format: %b >> false, Format: %B >> FALSE
param:true                     Format: %b >> true, Format: %B >> TRUE
param:false                    Format: %b >> true, Format: %B >> TRUE
param:0                        Format: %b >> true, Format: %B >> TRUE
param:A                        Format: %b >> true, Format: %B >> TRUE
---------------------------------- printHash() ----------------------------------
param:true                     Format: %h >> 4cf, Format: %H >> 4CF
param:false                    Format: %h >> 4d5, Format: %H >> 4D5
param:true                     Format: %h >> 36758e, Format: %H >> 36758E
param:0                        Format: %h >> 0, Format: %H >> 0
param:A                        Format: %h >> 41, Format: %H >> 41
---------------------------------- printStr() ----------------------------------
param:true                     Format: %s >> true, Format: %S >> TRUE
param:false                    Format: %s >> false, Format: %S >> FALSE
param:true                     Format: %s >> true, Format: %S >> TRUE
param:0                        Format: %s >> 0, Format: %S >> 0
param:A                        Format: %s >> A, Format: %S >> A
---------------------------------- printChar() ----------------------------------
param:65                       Format: %c >> A, Format: %C >> A
param:97                       Format: %c >> a, Format: %C >> A
param:A                        Format: %c >> A, Format: %C >> A
---------------------------------- printInt() ----------------------------------
param:65                       Format: %d >> 65
param:97                       Format: %d >> 97
param:9223372036854775807      Format: %d >> 9223372036854775807
---------------------------------- printOct() ----------------------------------
param:100                      Format: %o >> 144
param:200                      Format: %o >> 310
param:0                        Format: %o >> 0
param:9223372036854775807      Format: %o >> 777777777777777777777
---------------------------------- printHex() ----------------------------------
param:100                      Format: %x >> 64, Format: %X >> 64
param:200                      Format: %x >> c8, Format: %X >> C8
param:0                        Format: %x >> 0, Format: %X >> 0
param:9223372036854775807      Format: %x >> 7fffffffffffffff, Format: %X >> 7FFFFFFFFFFFFFFF
---------------------------------- printExp() ----------------------------------
param:1.0E8                    Format: %e >> 1.000000e+08, Format: %E >> 1.000000E+08
param:2.0E8                    Format: %e >> 2.000000e+08, Format: %E >> 2.000000E+08
param:3.0E8                    Format: %e >> 3.000000e+08, Format: %E >> 3.000000E+08
param:4.0E8                    Format: %e >> 4.000000e+08, Format: %E >> 4.000000E+08
param:9223372036854775807      Format: %e >> 9.223372e+18, Format: %E >> 9.223372E+18
---------------------------------- printFlo() ----------------------------------
param:1.0E8                    Format: %f >> 100000000.000000
param:2.0E8                    Format: %f >> 200000000.000000
param:3.0E8                    Format: %f >> 300000000.000000
param:4.0E8                    Format: %f >> 400000000.000000
param:9223372036854775807      Format: %f >> 9223372036854775807.000000


  

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java中的printf和println都是输出语句,但它们的输出方式有所不同。 printf函数可以根据指定的格式化字符串输出内容,可以用来实现更加灵活的输出方式。具体用法如下: ```java System.out.printf("格式化字符串", 参数1, 参数2, ...); ``` 格式化字符串中用百分号(%)表示占位符,具体格式化方式根据占位符的类型不同而有所变化。常见的占位符类型包括: - %d:输出整数类型(int、long等)数据。 - %f:输出浮点数类型(float、double等)数据。 - %s:输出字符串类型数据。 - %c:输出字符类型(char)数据。 例如,下面的代码段可以输出一个整数和一个字符串: ```java int num = 123; String str = "Hello world!"; System.out.printf("num=%d, str=%s\n", num, str); ``` 输出结果为: ``` num=123, str=Hello world! ``` 与之不同的是,println函数直接输出参数并换行,不需要指定格式化字符串: ```java System.out.println("Hello world!"); ``` 输出结果为: ``` Hello world! ``` 因此,printf函数可以根据需要格式化输出数据,而println函数则适合直接输出简单的文本内容。 ### 回答2: Java中的printf和println是用于输出的两个常见方法。它们在一些方面有着显著的不同。 首先,printf是一个格式化输出方法,可以根据指定的格式输出数据,而println则是在每个输出语句的末尾默认添加一个换行符。这意味着printf可以在一行上输出多个变量,并且可以根据需要格式化输出的样式。例如,我们可以使用printf按照指定的格式输出一个整数和一个浮点数,如下所示: int age = 25; double salary = 5000.50; System.out.printf("年龄:%d,薪水:%.2f", age, salary); 这将输出:年龄:25,薪水:5000.50。我们可以看到,printf可以使用占位符(%d和%.2f)来指定输出格式,并在输出时替换为相应的变量值。 其次,printf可以在输出时控制字符串的对齐方式和宽度。我们可以使用%-10s来指定输出字符串的左对齐,并且保证输出字符串的宽度为10个字符。例如: String name = "张三"; System.out.printf("名字:%10s", name); 这将输出:名字: 张三。我们可以看到,printf可以根据需要调整字符串的对齐和宽度。 综上所述,printf和println在输出方式上有所不同。printf提供了更灵活的格式化输出功能,可以自定义输出样式,并根据需要调整对齐方式和宽度。而println则是一种简单的输出方法,仅用于输出结果并在末尾添加换行符。 ### 回答3: Java中的printf是一个格式化输出方法,它允许我们根据指定的格式将数据格式化后输出。与之不同的是,println是用于打印一行文本或变量的方法。 在使用printf时,我们需要指定一个格式化字符串作为第一个参数,后续参数为要填充到格式化字符串中的值。格式化字符串可以包含普通字符和格式说明符。格式说明符以百分号(%)开头,并且可以指定输出的数据类型及其格式。 例如,我们可以使用printf输出一个整数和一个浮点数: int num = 10; float f = 3.14f; System.out.printf("整数:%d, 浮点数:%f", num, f); 这里,%d是用于格式化整数,%f是用于格式化浮点数。输出结果为:"整数:10, 浮点数:3.140000"。 与之相比,println只需要简单地打印出变量的值,不需要指定格式。例如: int num = 10; float f = 3.14f; System.out.println("整数:" + num); System.out.println("浮点数:" + f); 运行结果为: 整数:10 浮点数:3.14 可以看出,使用printf可以更灵活地控制输出的格式,包括小数点位数、百分比、日期、货币等的格式化,而println则直接输出变量的值。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值