Java.util.Formatter 类

java.util.Formatter.toString() 方法返回在输出目标上调用 toString() 的结果.

语法

public String toString()
  • 1

参数

无需参数。

返回值

返回在输出目标上调用 toString() 的结果。

异常

如果此格式化程序已被关闭,则抛出 FormatterClosedException调用其 close() 方法。

示例:

下面的示例显示 java.util.Formatter.toString() 方法。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建格式化程序对象
    Formatter formatter = new Formatter();
   
    //格式化字符串
    String name = "John";
    int age = 25;
    formatter.format("%s is %d years old.", name, age);

    //打印格式化字符串
    System.out.println(formatter);

    //打印格式化字符串
    //使用toString方法
    System.out.println(formatter.toString());   
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

上述代码的输出将是:

John is 25 years old.
John is 25 years old.
  • 1
  • 2