Java.io.PrintWriter.printf() 方法



描述

java.io.PrintWriter.printf() 方法是一個便捷方法,用於使用指定的格式字串和引數將格式化的字串寫入此寫入器。如果啟用了自動重新整理,則對該方法的呼叫將重新整理輸出緩衝區。

宣告

以下是java.io.PrintWriter.printf() 方法的宣告。

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

引數

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

  • args − 格式字串中格式說明符引用的引數。如果引數多於格式說明符,則忽略多餘的引數。引數的數量是可變的,可以為零。引數的最大數量受 Java 虛擬機器規範中定義的 Java 陣列的最大維度限制。空引數的行為取決於轉換。

返回值

此方法返回此寫入器。

異常

  • IllegalFormatException − 如果格式字串包含非法語法、與給定引數不相容的格式說明符、給定格式字串的引數不足或其他非法條件。有關所有可能的格式錯誤的規範,請參見格式化程式類規範的“詳細資訊”部分。

  • NullPointerException − 如果 format 為 null。

示例

以下示例演示了java.io.PrintWriter.printf() 方法的用法。

package com.tutorialspoint;

import java.io.*;
import java.util.Locale;

public class PrintWriterDemo {
   public static void main(String[] args) {
      String s = "Hello World";
      
      try {
         // create a new writer
         PrintWriter pw = new PrintWriter(System.out);

         // printf text with default locale.
         // %s indicates a string will be placed there, which is s
         pw.printf("This is a %s program", s);

         // change line
         pw.println();

         // printf text with default locale
         // %d indicates a integer will be placed there, which is 100
         pw.printf("This is a %s program with %d", s, 100);

         // flush the writer
         pw.flush();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

This is a Hello World program
This is a Hello World program with 100
java_io_printwriter.htm
廣告
© . All rights reserved.