java string printf_Java PrintWriter printf(String, Object)用法及代码示例

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

用法:

public PrintWriter printf(String format, Object…args)

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

format这是格式化字符串的格式。

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

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

异常:此方法引发以下异常:

NullPointerException如果格式为null,则抛出该错误。

IllegalFormatException如果指定的格式不合法或参数不足,则抛出该错误。

下面的方法说明了printf(String,Object)方法的用法:

程序1:

// Java program to demonstrate

// PrintWriter printf(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 printf() method

writer.printf(format, arg);

writer.flush();

}

catch (Exception e) {

System.out.println(e);

}

}

}

输出:

GeeksForGeeks 47.65734000

程序2:

// Java program to demonstrate

// PrintWriter printf(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 printf() method

writer.printf(format, arg1, arg2);

writer.flush();

}

catch (Exception e) {

System.out.println(e);

}

}

}

输出:

A Computer Science Portal GFG, GFG and GeeksforGeeks

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值