Java中的 ChoiceFormat applyPattern() 方法及示例
Java.text.ChoiceFormat类的applyPattern()方法用于通过覆盖当前限制和格式来设置当前 ChoiceFormat 的新模式文本。这种新模式将是 ChoiceFormat 的限制和格式的组合
句法:
public void applyPattern(String newPattern)
参数:此方法以newPattern作为参数,这是 ChoiceFormat 的新文本模式。
返回值:此方法不返回任何内容。
异常:如果指定的 newPattern 为 null,则此方法抛出NullPointerException 。
以下是说明applyPattern()方法的示例:
示例 1:
Java
// Java program to demonstrate applyPattern() method
import java.text.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
// creating and initializing limit
double[] limit = { 1, 2, 3 };
// creating and initializing format
String[] format = { "sun", "mon", "tue" };
// creating and initializing ChoiceFormat
ChoiceFormat cf
= new ChoiceFormat(limit, format);
// display the result
System.out.println("current pattern : "
+ cf.toPattern());
// applying the new pattern
// using applyPattern() method
cf.applyPattern("4#wed| 5#thu | 6#fri | 7#sat");
// display the result
System.out.println("\nnew pattern : "
+ cf.toPattern());
}
}
Java
// Java program to demonstrate applyPattern() method
import java.text.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
try {
// creating and initializing limit
double[] limit = { 1, 2, 3 };
// creating and initializing format
String[] format = { "sun", "mon", "tue" };
// creating and initializing ChoiceFormat
ChoiceFormat cf
= new ChoiceFormat(limit, format);
// display the result
System.out.println("current pattern : "
+ cf.toPattern());
// applying the new pattern
// using applyPattern() method
cf.applyPattern(null);
// display the result
System.out.println("\nnew pattern : "
+ cf.toPattern());
}
catch (NullPointerException e) {
System.out.println("\nString is Null");
System.out.println("Exception thrown : " + e);
}
}
}
输出:
current pattern : 1.0#sun|2.0#mon|3.0#tue
new pattern : 4.0#wed|5.0#thu |6.0#fri |7.0#sat
示例 2:
Java
// Java program to demonstrate applyPattern() method
import java.text.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
try {
// creating and initializing limit
double[] limit = { 1, 2, 3 };
// creating and initializing format
String[] format = { "sun", "mon", "tue" };
// creating and initializing ChoiceFormat
ChoiceFormat cf
= new ChoiceFormat(limit, format);
// display the result
System.out.println("current pattern : "
+ cf.toPattern());
// applying the new pattern
// using applyPattern() method
cf.applyPattern(null);
// display the result
System.out.println("\nnew pattern : "
+ cf.toPattern());
}
catch (NullPointerException e) {
System.out.println("\nString is Null");
System.out.println("Exception thrown : " + e);
}
}
}
输出:
current pattern : 1.0#sun|2.0#mon|3.0#tue
String is Null
Exception thrown : java.lang.NullPointerException
参考: https://docs.oracle.com/javase/9/docs/api/ Java/text/ChoiceFormat.html#applyPattern-java.lang.String-