📌  相关文章
📜  Java中的 PrintWriter format(String, Object) 方法及示例

📅  最后修改于: 2022-05-13 01:55:04.594000             🧑  作者: Mango

Java中的 PrintWriter format(String, Object) 方法及示例

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

句法:

参数:此方法接受两个强制参数:

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

返回值:此方法返回此 PrintWriter 实例。

异常:此方法抛出以下异常:

  • NullPointerException如果格式为空,则抛出此异常。
  • IllegalFormatException如果指定的格式非法或参数不足,则抛出此异常。

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

方案一:

// 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

方案二:

// 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  %1$s, %1$s 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