`

System.out.format的使用

    博客分类:
  • Java
阅读更多

JDK5.0允许象C语言那样直接用printf()方法来格式化输出,并且提供了许多参数来格式化输入,调用也很简单:

System.out.format("Pi is approximately  %f", Math.Pi);

   System.out.printf("Pi is approximately  %f", Math.Pi);

 printf()和 format() 方法具有相同的功能. System.out 是 java.io.PrintStream的实例PrintStreamjava.io.PrintWriter, 和 java.lang.String 每个类都有四个新的格式化方法:

format( String format, Object... args);

printf( String format, Object... args);

format( Locale locale, String format, Object... args);

printf( Locale locale, String format, Object... args);

 

同时,以前的formatter类也提供了更完善的方法来格式化,例如:

formatter.format("Pi is approximately %1$f," +

        "and e is about %2$f", Math.PI, Math.E);

 

格式化元素的构成如下:

%[argument_index$][flags][width][.precision]conversion

其中:

argument_index是一个正整数,说明了参数的位置,1为取第一个参数

width表示输出的最小字母个数

precision代表数字的小数位数

conversion代表被格式化的参数的类型:

f  float,

t  time

d  decimal

o octal

x  hexadecimal

s  general

c  a Unicode character

以下是个例子:

package format;

 

   import java.util.Formatter;

 

   public class UsingFormatter {

 

     public static void main(String[] args) {

       if (args.length != 1) {

         System.err.println("usage: " +

           "java format/UsingFormatter ");

         System.exit(0);

       }

       String format = args[0];

 

       StringBuilder stringBuilder = new StringBuilder();

       Formatter formatter = new Formatter(stringBuilder);

       formatter.format("Pi is approximately " + format +

         ", and e is about " + format, Math.PI, Math.E);

       System.out.println(stringBuilder);

     }

   }

 

//控制台调用

java format/UsingFormatter %f

//输出

Pi is approximately 3.141593, and e is about 2.718282

//控制台调用

java format/UsingFormatter %.2f

//输出

Pi is approximately 3.14, and e is about 2.72

//控制台调用

java format/UsingFormatter %6.2f

//输出(有空格来填补长度)

Pi is approximately   3.14, and e is about   2.72

//控制台调用

java format/UsingFormatter  %1$.2f

//输出

Pi is approximately 3.14, and e is about 3.14

 

//改变区域设置

package format;

 

   import java.util.Formatter;

   import java.util.Locale;

 

   public class UsingFormatter {

 

     public static void main(String[] args) {

       if (args.length != 1) {

         System.err.println("usage: " +

           "java format/UsingFormatter <format string>");

         System.exit(0);

       }

       String format = args[0];

 

       StringBuilder stringBuilder = new StringBuilder();

       Formatter formatter = new Formatter(stringBuilder,

                                   Locale.FRANCE);

       formatter.format("Pi is approximately " + format +

         ", and e is about " + format, Math.PI, Math.E);

       System.out.println(stringBuilder);

     }

   }

//控制台调用

java format/UsingFormatter %.2f

//输出

Pi is approximately 3,14, and e is about 2,72

 

//采用format,printf的可替代写法

package format;

 

   public class UsingSystemOut {

 

     public static void main(String[] args) {

       if (args.length != 1) {

         System.err.println("usage: " +

           "java format/UsingSystemOut <format string>");

         System.exit(0);

       }

       String format = args[0];

 

       System.out.format("Pi is approximately " + format +

         ", and e is approximately " + format, Math.PI, Math.E);

     }

   }

//控制台调用

java format/UsingSystemOut %.2f%n

//输出

Pi is approximately 3.14

   , and e is about 2.72

 

对时间的格式化用字母t来代表,通常在t后面加上特殊的字符来显示时间的某个部分:

tr  hour and minute,

tA  the day of the week

tB  the name of the month

te  the number of the day of the month

tY  the year

//eg.

package format;

 

   import java.util.Calendar;

 

   public class FormattingDates  {

 

     public static void main(String[] args) {

       System.out.printf("Right now it is %tr on " +

                         "%<tA, %<tB %<te, %<tY.%n",

                         Calendar.getInstance());

     }

   }

//说明:“<”指示采用的参数为前一个被格式化的参数

//输出

Right now it is 01:55:19 PM on Wednesday, September 22, 2004.

分享到:
评论

相关推荐

    EmvReader Java Code

    System.out.println("#ERROR# Invalid reader index format '"+args[0]+"'" ); System.exit(3);// throw new Exception( "Invalid reader index '"+args[0]+"'" ); } if ( iReader &gt;= terminals.size() ) {...

    kuhuesocket

    System.out.println("***************欢迎使用青鸟超市管理系统***************"); do{ System.out.println("1 .登陆 \n2 .退出系统"); System.out.println("******************请选择数字1/2*************...

    操作系统Java实现SJF代码

    public class SJF { public static void main(String[] args) { Scanner in= new Scanner(System.in);... System.out.println("平均周转时间为:"+df.format(AverageWT)); System.out.println

    LocalDateTimeUtil.java

    import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; public class LocalDateTimeUtil { /** * 比较 localDateTime2 是否在localDateTime1之前(比较大小) * @param ...

    java获取年月日,加减运算

    Calendar cal = Calendar.getInstance();... System.out.println(parse +"fsgfsf"+format ); cal.setTime(parse); int year1= cal.get(Calendar.YEAR);//获取年份 System.out.println("dssssssssssss"+year1);

    Java中格式化输出的几种方法

     System.out.format(“x = %5x”, x);  输出结果为:x = 37  2、System.out.format() int x = 55;  System.out.printf(“x = \u201d, x);  输出结果为:x = 7  3、String.format() String提供的静态...

    JDK8及以上版本的odbc驱动

    由于JDK8把ODBC驱动删除了... System.out.println("记录时间:" + df.format(rst.getDate("LOGTIME"))); } } catch (Exception e) { e.printStackTrace(); } System.out.println("closed connect"); } }

    java DATE与时间戳互化

    String d = format.format(time); Date date=format.parse(d); System.out.println("Format To String(Date):"+d); System.out.println("Format To Date:"+date); 运行结果: Format To String(Date):...

    Java超市会员管理系统(时间类)

    System.out.println(date); //将日期和时间按的格式变成我们要求的格式"年-月-日" SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String sdate=formater.format(date); System.out....

    汉王打卡机sdk

    System.out.println(faceId_ErrorCode); FaceIdAnswer output =new FaceIdAnswer(); // answer.answer=""; String Command = "GetRecord(start_time='2018-05-15 12:36:36' end_time=\"" + new SimpleDateFormat...

    实现视频在线播放.zip

    if (format.equalsIgnoreCase("mp4")) { response.addHeader("Content-Type","video/mp4;cahrset:utf-8"); }else { System.out.println("格式有误!"); } IOUtils.copy(inputStream, response....

    餐厅点餐点菜系统,有菜单、顾客输入菜名号码,生成菜单

    this.date=format.format(date); list=new LinkedList(); } public List&lt;Dish&gt; getList() { return list; } public void setList(List&lt;Dish&gt; list) { this.list = list; } public double getSumMoney() { ...

    struts2文件上传,与struts2-xml校验

    System.out.println("aaa="+ServletActionContext.getActionContext(ServletActionContext.getRequest())); filename=new String[myFile.length]; //获取跟文件夹的绝对路径,"/"代表获取跟路径 String path=...

    视音频最经典名著 Video Demystified

    4:1:1 YCbCr Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 4:2:0 YCbCr Format . . . . . . . . . . . . . . . . . . . . . . ....

    RfidIInventoryCSVTool

    System.out.println("Please make sure the input file format are '*.csv'.");System.out.println("Please make sure extra information in input file has been deleted.");System.out.println("And headers ...

    java常用工具类的使用

    Date bir=format.parse(birthday); System.out.println(bir); } catch (ParseException e) { ① // TODO Auto-generated catch block e.printStackTrace(); } } } 代码解析: ① 用SimpleDateFormat解析日期...

    汉字转拼音

    import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import ...

    java倒计时源代码 原创

    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)); System.out.println("下班倒计时开始..."); timer.schedule(new MyTask(date),0,1000); } //ps:如有不懂请联系作者!解压后是...

    java时间处理工具类--CalendarUtil(java源码)

    System.out.println("First day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByWeek(new Date()))); System.out.println("Last day of week is : " + new ...

    Thinking in Java 4th Edition

    What’s Inside Preface 1 Java SE5 and SE6 .................. 2 Java SE6 ............................................The 4th edition...........................Changes ...........................................

Global site tag (gtag.js) - Google Analytics