📌  相关文章
📜  Java中的 ChoiceFormat parse() 方法和示例

📅  最后修改于: 2022-05-13 01:55:46.784000             🧑  作者: Mango

Java中的 ChoiceFormat parse() 方法和示例

Java.text.ChoiceFormat类的parse()方法用于获取 ChoiceFormat 对象中特定格式的限制值。

句法:

public Number parse(String text, ParsePosition status)

参数:此方法采用以下参数:

  • 文本:这是必须以字符串格式找到限制值的文本。
  • 状态:这是该选项项所在的索引,用于找到哪个限制值。

返回值:此方法返回一个指定类型的数组,该数组是附加到 ChoiceFormat 对象的格式。

异常:如果字符串文本或状态为空,此方法将抛出NullPointerException

以下是说明parse()方法的示例:

示例 1:

// Java program to demonstrate
// getFormats() method
  
import java.text.*;
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] argv)
    {
        try {
  
            // creating and initializing ChoiceFormat
            ChoiceFormat cf1
                = new ChoiceFormat(
                    "4#wed| 5#thu | 6#fri | 7#sat");
  
            // creating and initializing ParsePosition
            ParsePosition par = new ParsePosition(0);
  
            // getting limit of particular format
            // of ChoiceFormat Object
            // using getFormats() method
            Number limit
                = cf1.parse("wed", par);
  
            // display the result
            System.out.print("limit: "
                             + limit.intValue());
        }
        catch (NullPointerException e) {
            System.out.println("\nString is Null");
            System.out.println("Exception thrown: " + e);
        }
    }
}
输出:
limit: 4

示例 2:

// Java program to demonstrate
// getFormats() method
  
import java.text.*;
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] argv)
    {
        try {
  
            // creating and initializing ChoiceFormat
            ChoiceFormat cf1
                = new ChoiceFormat(
                    "4#wed| 5#thu | 6#fri | 7#sat");
  
            // creating and initializing ParsePosition
            ParsePosition par = new ParsePosition(0);
  
            // getting limit of particular format
            // of ChoiceFormat Object
            // using getFormats() method
            Number limit
                = cf1.parse(null, par);
  
            // display the result
            System.out.print("limit: "
                             + limit.intValue());
        }
        catch (NullPointerException e) {
            System.out.println("String is Null");
            System.out.println("Exception thrown: " + e);
        }
    }
}
输出:
String is Null
Exception thrown: java.lang.NullPointerException

参考: https://docs.oracle.com/javase/9/docs/api/ Java/text/ChoiceFormat.html#parse-java.lang.String-java.text.ParsePosition-