console用法java_Java Console printf(String, Object)用法及代码示例

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");

}

}

输出:

bc1e86c26b2abdafdf2de47ba22bcca6.png

程序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");

}

}

输出:

f54f4651eb19ca251ac010c266bf912f.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值