Java中PrintStream Class的format(String,Object)方法用于在流中打印格式化的字符串。该字符串使用指定的格式和作为参数传递的参数进行格式化。
用法:
public PrintStream format(String format, Object…args)
参数:此方法接受两个强制参数:
- format这是格式化字符串的格式。
- args这是格式化字符串的参数个数。它可以是可选的,即根据格式,无参数或任意数量的参数。
返回值:此方法返回此PrintStream实例。
异常:此方法引发以下异常:
- NullPointerException 如果格式为null,则抛出该错误。
- IllegalFormatException如果指定的格式不合法或参数不足,则抛出该错误。
下面的方法说明了format(String,Object)方法的用法:
程序1:
// Java program to demonstrate 
// PrintStream 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 PrintStream instance 
            PrintStream stream 
                = new PrintStream(System.out); 
  
            // print the formatted string 
            // to this stream using format() method 
            stream.format(format, arg); 
  
            stream.flush(); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
输出:
GeeksForGeeks 47.65734000
程序2:
// Java program to demonstrate 
// PrintStream 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 PrintStream instance 
            PrintStream stream 
                = new PrintStream(System.out); 
  
            // print the formatted string 
            // to this stream using format() method 
            stream.format(format, arg1, arg2); 
  
            stream.flush(); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
输出:
A Computer Science Portal GFG, GFG and GeeksforGeeks
相关用法
- Java PrintStream print(Object)用法及代码示例
- Java PrintStream println(Object)用法及代码示例
- Java PrintStream printf(String, Object)用法及代码示例
- Java PrintStream format(Locale, String, Object)用法及代码示例
- Java PrintStream printf(Locale, String, Object)用法及代码示例
- Java PrintStream write(int)用法及代码示例
- Java PrintStream print(int)用法及代码示例
- Java PrintStream flush()用法及代码示例
- Java PrintStream checkError()用法及代码示例
- Java PrintStream setError()用法及代码示例
- Java PrintStream close()用法及代码示例
- Java PrintStream clearError()用法及代码示例
- Java PrintStream println()用法及代码示例
- Java PrintStream println(int)用法及代码示例
- Java PrintStream write(byte[], int, int)用法及代码示例
注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 PrintStream format(String, Object) method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
