​​​​​​​ChoiceFormat类

ChoiceFormat类:

ChoiceFormat允许您将格式附加到一系列数字。它通常用于MessageFormat处理复数形式。使用升序的双精度列表指定选项,其中每个项指定直到下一项的半开区间:

 当且仅当limit [j] <= X <limit [j + 1]时,X匹配j

如果没有匹配,则使用第一个或最后一个索引,具体取决于数字(X)是太低还是太高。如果限制数组不按升序排列,则格式化结果将不正确。ChoiceFormat也接受\u221E等同于无穷大(INF)。

这里format()和parse()的调用和DateFormat类的调用方法相同。format(Choice->String)parse(String->Choice)

构造方法:

ChoiceFormat(double[] limits, String[] formats)   构造具有限制和相应的格式。
ChoiceFormat(String newPattern)  根据模式构造具有限制和相应格式。

其中newPattern书写的形式:doubleNum [#、<、\u2264(<=)] formatStr 如:1 # one。

可以有多个如:1 # one | 2 < two | 4 \u2264 three 之间用“ | ”符号隔开,且doubleNum必须为升序

其中比较常用的成员方法:

(1)applyPattern()方法,设置模式

(2)nextDouble(double d)方法,找到比d大的最小double值。如果是NaN,则返回相同的值。用于半开间隔。

(3)previousDouble(double d)方法,找到小于d的最大double值

(4)nextDouble(double d,boolean positive)方法,找到大于d的最小double数(如果positive==true),找到小于d的最大double数(如果positive==false)。如果是NaN,则返回相同的值。

更多详细方法参考https://docs.oracle.com/javase/6/docs/api/java/text/ChoiceFormat.html

实例:

package codeMessageFormat;
import java.text.ChoiceFormat;
public class ceshi {
	public static void main(String[] args) {
		//  当且仅当limit [j] <= X <limit [j + 1]时,X匹配j
		double []limits = {1,2,3,4,5,6,7};
		String []formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
		ChoiceFormat format = new ChoiceFormat(limits, formats);
		System.out.println(format.format(0));//0<1则只能匹配到索引0,0对应Sun
		System.out.println(format.format(6));//6<=6<7则6匹配到索引5,5对应Fri
		System.out.println(format.format(2.8));//2<2.8<3则2.8匹配到索引1,1对应Mon
		System.out.println(format.format(8));//8>7,只能匹配到索引6,6对应Sat	
		ChoiceFormat choice=new ChoiceFormat("1 # one | 2 < two | 4 \u2264 three");//第一个公式找接近1的,第二个公式找大于2的,第三个公式找大于等于4的
        System.out.println(choice.format(0));//0<1则匹配到1,对应one
        System.out.println(choice.format(1));//1<2则匹配到1,对应one
        System.out.println(choice.format(2));//2==2不符合第二个公式,则匹配到1,对应one
        System.out.println(choice.format(3));//3>2则匹配到2,对应two
        System.out.println(choice.format(4));//4==4则匹配到4,对应three
        System.out.println(choice.format(5));//5>4则匹配到4,对应three

	}

}
运行结果:
Sun
Fri
Mon
Sat
one 
one 
one 
two 
three
three

​​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值