Java PrintWriter format(String, Object)方法及实例

来源:这里教程网 时间:2026-02-17 21:06:52 作者:

Java PrintWriter format(String, Object)方法及实例

Java中PrintWriter类的format(String, Object)方法用于在流中打印一个格式化的字符串。字符串是使用指定的格式和作为参数传递的参数进行格式化。

语法。

public PrintWriter format(String format, Object…args)

参数。该方法接受两个强制性参数。

format是要对字符串进行格式化的格式。args是格式化字符串的参数数量。它可以是可选的,即没有参数或根据格式有任意数量的参数。

返回值。该方法返回这个PrintWriter实例。

异常。该方法抛出以下异常。

NullPointerException 如果格式是空的,会抛出这个异常。IllegalFormatException 如果指定的格式是非法的或者参数不足,则抛出此问题。

下面的方法说明了format(String, Object)方法的工作。

程序1:

// Java program to demonstrate// PrintWriter format(String, Object) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Get the parameters            double arg = 47.65734;              String format = "GeeksForGeeks %.8f";              // Create a PrintWriter instance            PrintWriter writer                = new PrintWriter(System.out);              // print the formatted string            // to this writer using format() method            writer.format(format, arg);              writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

GeeksForGeeks 47.65734000

程序2。

// Java program to demonstrate// PrintWriter format(String, Object) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Get the parameters              String arg1 = "GFG";            String arg2 = "GeeksforGeeks";              String format = "A Computer Science "                            + "Portal  %1s, %1s and %2$s";              // Create a PrintWriter instance            PrintWriter writer                = new PrintWriter(System.out);              // print the formatted string            // to this writer using format() method            writer.format(format, arg1, arg2);              writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

A Computer Science Portal  GFG, GFG and GeeksforGeeks

相关推荐