Java.io.Console.printf()方法範例


java.io.Console.printf(String fmt, Object... args) 方法編寫一個格式化字串使用指定格式字串和引數到這個控制台的輸出流。

宣告

以下是java.io.Console.printf(String format, Object... args)方法的宣告:

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

引數

  • format -- 一個格式字串在格式字串的語法描述

  • args -- 格式說明符在格式字串中的引數參照。

返回值

這個方法返回當前控制台(console)。

異常

  • IllegalFormatException -- 如果格式字串包含非法語法,格式說明符與給定的格式字串給定的,引數不足,或其他非法條件不符

例子

下面的範例演示java.io.Console.printf(String format, Object... args) 方法的用法。

package com.yiibai;

import java.io.Console;

public class ConsoleDemo {
   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.printft(fmt, "Items", "Quanity", "Price");
            cnsl.printft(fmt, "-----", "-----", "-----");
            cnsl.printft(fmt, "Tomato", "1Kg", "15");
            cnsl.printft(fmt, "Potato", "5Kg", "50");
            cnsl.printft(fmt, "Onion", "2Kg", "30");
            cnsl.printft(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