Java.io.Console.printf() 方法
描述
java.io.Console.format(String fmt, Object... args) 方法使用指定的格式字符串和参数将格式化字符串写入此控制台的输出流。
声明
以下是 java.io.Console.printf(String format, Object... args) 方法的声明 −
public Console printf(String format, Object... args)
参数
format − 格式字符串语法中描述的格式字符串
args − 格式字符串中的格式说明符引用的参数。
返回值
此方法返回此控制台。
异常
IllegalFormatException − 如果格式字符串包含非法语法、与给定格式不兼容的格式说明符、给定格式字符串的参数不足或其他非法条件
示例
下面的例子展示了 java.io.Console.printf(String format, Object... args) 方法的使用。
package com.tutorialspoint;
import java.io.Console;
public class ConsoleDemo {
public static void main(String[] args) {
Console cnsl = null;
try {
cnsl = System.console();
if (cnsl != null) {
String fmt = "%1$4s %2$10s %3$10s%n";
// format
cnsl.printft(fmt, "Items", "Quanity", "Price");
cnsl.printft(fmt, "-----", "-----", "-----");
cnsl.printft(fmt, "Tomato", "1Kg", "15");
cnsl.printft(fmt, "Potato", "5Kg", "50");
cnsl.printft(fmt, "Onion", "2Kg", "30");
cnsl.printft(fmt, "Apple", "4Kg", "80");
}
} catch(Exception ex) {
// if any error occurs
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Items Quantity Price ----- -------- ----- Tomato 1Kg 15 Potato 5Kg 50 Onion 2Kg 30 Apple 4Kg 80

