Java.io.Console.printf() 方法



描述

java.io.Console.format(String fmt, Object... args) 方法使用指定的格式字串和引數將格式化的字串寫入此控制檯的輸出流。

宣告

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

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

引數

  • format − 如格式字串語法中所述的格式字串

  • args − 格式字串中格式說明符引用的引數。

返回值

此方法返回此控制檯。

異常

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

示例

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

package com.tutorialspoint;

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
java_io_console.htm
廣告