Java Formatter toString() 方法



描述

java Formatter toString() 方法返回對輸出目標呼叫 toString() 的結果。

宣告

以下是java.util.Formatter.toString() 方法的宣告

public String toString()

引數

返回值

此方法返回對輸出目標呼叫 toString() 的結果。

異常

FormatterClosedException − 如果此格式化程式已透過呼叫其 close() 方法關閉

美國地區設定的 Formatter 物件的字串表示示例

以下示例演示瞭如何使用 Java Formatter out() 方法列印格式化程式的目標。我們建立了一個帶有 StringBuffer 和美國地區設定的 formatter 物件。Formatter 用於使用 format() 方法列印字串。然後使用 toString() 方法列印其內容。

package com.tutorialspoint;

import java.util.Formatter;
import java.util.Locale;

public class FormatterDemo {
   public static void main(String[] args) {

      // create a new formatter
      StringBuffer buffer = new StringBuffer();
      Formatter formatter = new Formatter(buffer, Locale.US);

      // format a new string
      String name = "World";
      formatter.format("Hello %s !", name);

      // print the formatted string with default locale
      System.out.println("" + formatter);

      // print the formatter as a string
      System.out.println("" + formatter.toString());
	  
      formatter.close();
   }
}

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

Hello World !
Hello World !

德國地區設定的 Formatter 物件的字串表示示例

以下示例演示瞭如何使用 Java Formatter out() 方法列印格式化程式的目標。我們建立了一個帶有 StringBuffer 和德國地區設定的 formatter 物件。Formatter 用於使用 format() 方法列印字串。然後使用 toString() 方法列印其內容。

package com.tutorialspoint;

import java.util.Formatter;
import java.util.Locale;

public class FormatterDemo {
   public static void main(String[] args) {

      // create a new formatter
      StringBuffer buffer = new StringBuffer();
      Formatter formatter = new Formatter(buffer, Locale.GERMAN);

      // format a new string
      String name = "World";
      formatter.format("Hello %s !", name);

      // print the formatted string with default locale
      System.out.println("" + formatter);

      // print the formatter as a string
      System.out.println("" + formatter.toString());
	  
      formatter.close();
   }
}

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

Hello World !
Hello World !

法國地區設定的 Formatter 物件的字串表示示例

以下示例演示瞭如何使用 Java Formatter out() 方法列印格式化程式的目標。我們建立了一個帶有 StringBuffer 和法國地區設定的 formatter 物件。Formatter 用於使用 format() 方法列印字串。然後使用 toString() 方法列印其內容。

package com.tutorialspoint;

import java.util.Formatter;
import java.util.Locale;

public class FormatterDemo {
   public static void main(String[] args) {

      // create a new formatter
      StringBuffer buffer = new StringBuffer();
      Formatter formatter = new Formatter(buffer, Locale.FRENCH);

      // format a new string
      String name = "World";
      formatter.format("Hello %s !", name);

      // print the formatted string with default locale
      System.out.println("" + formatter);

      // print the formatter as a string
      System.out.println("" + formatter.toString());
	  
      formatter.close();
   }
}

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

Hello World !
Hello World !
java_util_formatter.htm
廣告
© . All rights reserved.