Java格式化字符串详解

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

  2 .排版格式的控制能力

  package string;

  import java.util.Formatter;

  public class Receipt {

  private double total = 0;

  private Formatter f = new Formatter(System.out);

  public void printTitle() {

  //-表示左对齐

  f.format(“%-15s %5s %10s\n”, “Item”, “Qty”, “Price”);

  f.format(“%-15s %5s %10s\n”, “—“, “—“, “—“);

  }

  public void print(String item, int qty, double price) {

  f.format(“%-15.15s %5d %10.2f\n”, item, qty, price);

  total += price;

  }

  public void printTotal() {

  f.format(“%-15s %5s %10.2f\n”, “Tax”, “”, total*0.06);

  f.format(“%-15s %5s %10s\n”, “”, “”, “—“);

  f.format(“%-15s %5s %10.2f\n”, “Total”, “”, total*1.06);

  }

  public static void main(String[] args) {

  Receipt r = new Receipt();

  r.printTitle();

  r.print(“big ice”, 2, 9);

  r.print(“little ice”, 1, 1.25);

  r.print(“old ice”, 5, 5.5);

  r.printTotal();

  }

  }

  //output

  Item Qty Price

  — — —

  big ice 2 9.00

  little ice 1 1.25

  old ice 5 5.50

  Tax 0.95

  —

  Total 16.70

  3.类型转换

  package string;

  import java.math.BigInteger;

  import java.util.Formatter;

  public class Conversion {

  public static void main(String[] args) {

  Formatter f = new Formatter(System.out);

  char u = ‘a’;

  System.out.println(“——–u = ‘a'”);

  f.format(“s: %s\n”, u); //字符串

  f.format(“c: %c\n”, u); //Unicode 字符

  f.format(“b: %b\n”, u); //boolean值

  f.format(“h: %h\n”, u); //16进制哈希值

  int v = 21;

  System.out.println(“\n———-v = 21”);

  f.format(“d: %d\n”, v); //十进制整数

  f.format(“c: %c\n”, v); //Unicode 字符

  f.format(“b: %b\n”, v); //boolean值

  f.format(“s: %s\n”, v); //字符串

  f.format(“x: %x\n”, v); //16进制整数

  f.format(“h: %h\n”, v); //16进制哈希值 hasCode–>toHex

  BigInteger w = new BigInteger(“5000000000000”);

  System.out.println(“\n——-w = new BigInteger(\”5000000000000\”)”);

  f.format(“d: %d\n”, w); //十进制整数

  f.format(“b: %b\n”, w); //boolean值

  f.format(“s: %s\n”, w); //字符串

  f.format(“x: %x\n”, w); //16进制整数

  f.format(“h: %h\n”, w); //16进制哈希值 hasCode–>toHex

  double x = 1234.567;

  System.out.println(“\n——-x = 1234.567”);

  f.format(“b: %b\n”, x); //boolean

  f.format(“s: %s\n”, x); //字符串

  f.format(“f: %f\n”, x); //float

  f.format(“e: %e\n”, x); //计算机科学记数法表示的十进制数

  f.format(“h: %h\n”, x); //16进制哈希值 hasCode–>toHex

  Conversion c = new Conversion();

  System.out.println(“\n——-c = new Conversion()”);

  f.format(“b: %b\n”, c); //boolean

  f.format(“s: %s\n”, c); //字符串

[1][2][3]

而在于当时的那份心情。可是旅行的彼时那刻我的心情一直是好的吗?

Java格式化字符串详解

相关文章:

你感兴趣的文章:

标签云: