格式化控制台输出

System.out.printf(format, item1, item2, ..., items)

标识符 输出 举例
%b boolean ture false
%c char ’a’
%d 十进制整数 200
%f float 45.460000
%e 标准科学记数法 4.556000e+01
%s string ”Java is cool”

可以在格式描述符后面加上精度限制

%5c
%6b
%5d
%10.2f
%10.2e
%12s


class Main{
  public static void main(String[] args){
    int count = 5;
    double amount = 45.56;
    System.out.printf("count is %d and amount is %f\n", count, amount);

    double x = 2.0 / 3;
    System.out.printf("x is %4.2f\n", x);
    System.out.printf("x is %6.3e\n", x);

    System.out.printf("%5c\n", 'a');
    System.out.printf("%6b\n", false);
    System.out.printf("%5d\n", 12);
    System.out.printf("%12s\n", "china");

    System.out.printf("%%\n");
    //默认右对齐
    System.out.printf("%8d%8s%8.1f\n", 1234, "Java", 5.6);
    //-改为左对齐
    System.out.printf("%-8d%-8s%-8.1f\n", 1234, "Java", 5.6);
    
  }
}

posted @   Scenery_Shelley  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示