介绍几个java.text.*包下的类
1. NumberFormat
1.1 作用
取当前系统的数字格式,比如货币
1.2 实例化
NumberFormat.getInstance();
1.3 常用方法
NumberFormat.parse(String str)
-- 返值为: String
-- 异常必须处理,否则报编译错误, Exception occurs when first char cannot be parsed;
-- 参数里不是每个字符都用得上,当遇到字符时,无法转成数字,参数就提取到non-numberic char
NumberFormat.format(long number);
-- 返值为: Number
-- 异常为runtime Exception,当参数为非数字时,运行时抛IllegalArgumentException,编译可以通过
1.4 代码实例
package com.ocjp.g11n;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class TestNumberFormat {
public static void main(String[] args) {
new TestNumberFormat().go();
}
public void go() {
NumberFormat nf, nf2;
Number n;
Locale[] la = NumberFormat.getAvailableLocales();
for(int x=0; x < 10; x++) {
nf = NumberFormat.getCurrencyInstance(la[x]);
System.out.println(nf.format(123.456f));
}
nf2 = NumberFormat.getInstance();
try {
//exception must be handled or declared; if the first char cannot be parsed, it will throw out ParseException;
//NumberFormat.parse() will return Number, pay attention that not fully String will be used, for this case, f will be discarded;
//not all String will be used,
n = nf2.parse("123.456f");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//NumberFormat.fortmat(long number); the parameter must be Number; it returns String;
//IllegalArugmentException(Runtime Exception, not checked at compiling time) will be thrown out at running time if pass an non-Number parameter;
// System.out.println(nf2.format("123.456"));
System.out.println(nf2.format(123.456));
}
}
//Output
RM123.46
ر.ق. 123.46
123, kr.
123,46 €
¤ 123,46
€123.46
SFr. 123.46
123,46 €
ر.س. 123.46
د.ع. 123.456
123.456
2 Calendar
月份的范围是0-11,也就是说0代表1月
常用方法:
Calendar.add(); 既改变大的字段,又改变小的字段
Calendar.roll(); 只改变小的字段
代码一:
import java.util.*;
public class Wise {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(1999,11,25); //MONTH is [0-11]; This is Dec.25th, 1999;
// roll() doesn't change the bigger field(YEAR in this case); only change smaller field(DAY in this case);
c.roll(Calendar.MONTH, 3);
System.out.println(c.getTime()); //Output is Mar. 25th, 1999;
// add() will change both bigger and smaller field;
c.add(Calendar.DATE, 10);
System.out.println(c.getTime());
}
}
Output:
Thu Mar 25 13:57:07 EST 1999
Sun Apr 04 13:57:07 EDT 1999
代码二:
package com.ocjp.g11n;
import java.util.*;
public class CalendarTest {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(1999,8,31); //MONTH是从0-11;所以这里实际上是指1999年9月31日,因为9月没有31日,实际上就转成了1999年10月1日;
System.out.println(c.getTime());
c.roll(Calendar.MONTH, 11);
System.out.println(c.getTime());
c.add(Calendar.DATE, 10);
System.out.println(c.getTime());
}
}
Output:
Fri Oct 01 14:03:05 EDT 1999
Wed Sep 01 14:03:05 EDT 1999
Sat Sep 11 14:03:05 EDT 1999