« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9696069 建立时间:2004年12月20日 |

| |
[java语言]使用tiger编程 原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2006/7/16 15:30:09 |
1.字符串的格式化java的字符串的格式化比较麻烦,大家可以看一下获取时间的格式,需要用到一个专门用于时间格式的类java.text.SimpleDateFormat。接下来我们使用这个 SimpleDateFormat把当前时间格式化为一个如下格式的时间字符串XXXX年XX月XX日_XX时XX分XX秒,代码:java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(formatter.format(Calendar.getInstance().getTime())); 获取时间格式的函数是format,这个函数的参数是java.util.Date对象。格式化数值DecimalFormat f=new DecimalFormat("0000"); System.out.println(f.format(1));输出 "0001"JDK5.0允许象C语言那样直接用printf()方法来格式化输出,并且提供了许多参数来格式化输入。printf()和 format() 方法具有相同的功能. System.out 是 java.io.PrintStream的实例. PrintStream, java.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);例如String s = String.format ("Welcome %s at %s", "Real's HowTo", "http://www.rgagnon.com");// output : Welcome Real's HowTo at http://www.rgagnon.com
可以使用字符串数组,这样就不用讨厌的MessageFormatSystem.out.printf(Locale.CHINA,"Welcome %s at %s", new Object[]{"Real's HowTo", "http://www.rgagnon.com"});String a[] = { "Real's HowTo", "http://www.rgagnon.com" }; String s = String.format("Welcome %s at %s", a); System.out.println(s);Object a[] = { "Real's HowTo", "http://www.rgagnon.com", java.util.Calendar.getInstance() };tr hour and minute,tA the day of the weektB the name of the monthte the number of the day of the monthtY the yearString s = String.format("Welcome %1$s at %2$s ( %3$tY %3$tm %3$te )", a);System.out.println(s);输出 Welcome Real's HowTo at http://www.rgagnon.com ( 2007 07 23 )数组转为表格式 String format = "|%1$-10s|%2$-10s|%3$-20s|\n"; System.out.format(format, new Object[]{"FirstName", "Init.", "LastName"}); System.out.format(format, new Object[]{"Real", "", "Gagnon"}); System.out.format(format,new Object[]{ "John", "D", "Doe"});
String ex[] = { "John", "F.", "Kennedy" };
System.out.format(format, (Object[])ex);Formatter类也提供了更完善的方法来格式化%[argument_index$][flags][width][.precision]conversion其中:argument_index是一个正整数,说明了参数的位置,1为取第一个参数width表示输出的最小字母个数precision代表数字的小数位数conversion代表被格式化的参数的类型:f float,t timed decimalo octalx hexadecimals generalc a Unicode character例子 Formatter fmt = new Formatter(); fmt.format("|%-10.2f|", new Object[]{new Double(123.123)}); System.out.println(fmt);2.Integer的转换Integer count = new Integer(0);应该这样写Integer count =Integer.valueOf(0);返回一个表示指定的 int 值的 Integer 实例。如果不需要新的 Integer 实例,则通常应优先使用该方法,而不是构造方法 Integer(int),因为该方法有可能通过缓存经常请求的值而显著提高空间和时间性能。至少整数在-128至127之间这样写。 |
|
|