Java Console printf()方法

java.io.Console.printf(String fmt, Object... args) 用于将字符串写入控制台输出流。

1 语法

public Console printf(String format, Object... args)

2 参数

format:格式字符串语法中描述的格式字符串

args:格式字符串中格式说明符引用的参数。

3 返回值

返回Console对象。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.Console.printf(String fmt, Object... args)法的例子
 */
import java.io.Console;

public class Demo {
    public static void main(String[] args) {
        Console cnsl = null;

        try {
            cnsl = System.console();

            if (cnsl != null) {
                String fmt = "%1$4s %2$10s %3$10s%n";

                // format
                cnsl.printf(fmt, "Items", "Quanity", "Price");
                cnsl.printf(fmt, "-----", "-----", "-----");
                cnsl.printf(fmt, "Tomato", "1Kg", "15");
                cnsl.printf(fmt, "Potato", "5Kg", "50");
                cnsl.printf(fmt, "Onion", "2Kg", "30");
                cnsl.printf(fmt, "Apple", "4Kg", "80");
            }

        } catch(Exception ex) {
            // if any error occurs
            ex.printStackTrace();
        }
    }
}

输出结果为:

Items      Quantity      Price
-----      --------      -----
Tomato     1Kg           15
Potato     5Kg           50
Onion      2Kg           30
Apple      4Kg           80

热门文章

优秀文章