格式化控制台输出

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 @ 2022-05-11 12:14  Scenery_Shelley  阅读(43)  评论(0)    收藏  举报