Java中Console类的printf(String,Object)方法用于将格式化的字符串写入控制台的输出流。它使用指定的格式字符串和参数。这是一种方便的方法。
用法:
public Console printf(String fmt,
Object... args)
参数:此方法接受两个参数:
fmt-它表示字符串的格式。
args-它表示由字符串格式的格式说明符引用的参数。
返回值:此方法返回控制台。
异常:如果字符串格式包含非法语法,或者格式说明符与给定参数不兼容,或者给定格式字符串或其他非法条件,则此方法将引发IllegalFormatException。
注意:System.console()在在线IDE中返回null。
以下示例程序旨在说明IO包中Console类中的printf(String,Object)方法:
程序1:
// Java program to illustrate
// Console printf(String, Object) method
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// Create the console object
Console cnsl
= System.console();
if (cnsl == null) {
System.out.println(
"No console available");
return;
}
String fmt = "%1$4s %2$10s %3$10s%n";
cnsl.printf(fmt, "Books", "Author", "Price");
cnsl.printf(fmt, "-----", "------", "-----");
cnsl.printf(fmt, "DBMS", "Navathe", "800");
cnsl.printf(fmt, "Algorithm", "Cormen", "925");
cnsl.printf(fmt, "Operating System", "Rajib Mall", "750");
}
}
输出:
程序2:
// Java program to illustrate
// Console printf(String, Object) method
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// Create the console object
Console cnsl
= System.console();
if (cnsl == null) {
System.out.println(
"No console available");
return;
}
String fmt = "%1$4s %2$10s %3$10s%n";
cnsl.printf(fmt, "Items", "Quantity", "Price");
cnsl.printf(fmt, "-----", "------", "-----");
cnsl.printf(fmt, "Tomato", "1 Kg", "80");
cnsl.printf(fmt, "Apple", "3 Kg", "500");
cnsl.printf(fmt, "Potato", "2 Kg", "75");
}
}
输出: