Java Java.io.Console.format()方法

  • 描述

    java.io.Console.format(String fmt, Object... args)方法使用指定的格式字符串参数将格式化的字符串写入此控制台的输出流。
  • 声明

    以下是java.io.Console.format(String fmt, Object... args)方法的声明-
     public Console format(String fmt, Object... args)
  • 参数

    • fmt格式字符串语法中描述的格式字符串
    • args格式字符串中格式说明符引用的参数。
  • 返回值

    此方法返回此控制台。
  • 异常

    IllegalFormatException如果格式字符串包含非法语法,与给定格式不兼容的格式说明符,给定格式字符串的参数不足或其他非法条件
  • 例子

    以下示例显示java.io.Console.format(String fmt,Object ... args)方法的用法。
     
    package com.jc2182;
    import java.io.Console;
    
    public class ConsoleDemo {
       public static void main(String[] args) {      
          Console cnsl = null;
          
          try {
             cnsl = System.console();
    
             if (cnsl != null) {
                String fmt = "%1$4s %2$10s %3$10s%n";
                
                // format
                cnsl.format(fmt, "Items", "Quanity", "Price");
                cnsl.format(fmt, "-----", "-----", "-----");
                cnsl.format(fmt, "Tomato", "1Kg", "15");
                cnsl.format(fmt, "Potato", "5Kg", "50");
                cnsl.format(fmt, "Onion", "2Kg", "30");
                cnsl.format(fmt, "Apple", "4Kg", "80");
             } 
             
          } catch(Exception ex) {
             // if any error occurs
             ex.printStackTrace();      
          }
       }
    }
    
    让我们编译并运行以上程序,这将产生以下结果-
     
    Items      Quantity      Price
    -----      --------      -----
    Tomato     1Kg           15
    Potato     5Kg           50
    Onion      2Kg           30
    Apple      4Kg           80