Java Console.format(String fmt, Object ... args)方法範例

2019-10-16 22:14:32

Java Console.format(String fmt, Object … args)方法範例

Console.format(String fmt, Object ... args)的語法如下所示。

public Console format(String fmt,  Object ... args)

範例

在下面的程式碼顯示如何使用Console.format(String fmt, Object ... args)方法。

import java.io.Console;

public class Main {
  public static void main(String[] args) throws Exception {

    Console cnsl = System.console();

    if (cnsl != null) {
      String fmt = "%1$4s %2$10s %3$10s%n";

      // format
      cnsl.format(fmt, "Items", "Level", "Price");
      cnsl.format(fmt, "-----", "-----", "-----");
      cnsl.format(fmt, "PHP", "1", "15");
      cnsl.format(fmt, "CSS", "2", "50");
      cnsl.format(fmt, "Java", "3", "30");
      cnsl.format(fmt, "HTML", "4", "80");
    }

  }
}

上面的程式碼生成以下結果。

F:\website\yiibai\worksp\src>java Main
Items      Level      Price
-----      -----      -----
 PHP          1         15
 CSS          2         50
Java          3         30
HTML          4         80