当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java MessageFormat parse()方法用法及代码示例


java.text.MessageFormat类的parse()方法用于从索引的开头解析字符串对象。

用法:

public Object[] parse(String source)
               throws ParseException

参数:此方法将字符串源作为参数,对其进行解析。



返回值:此方法返回对象数组作为输出。

异常:如果无法分析指定字符串的开头,则此方法将引发ParseException。

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

范例1:

// Java program to demonstrate 
// parse() method 
  
import java.text.*; 
import java.util.*; 
import java.io.*; 
  
public class GFG { 
    public static void main(String[] argv) 
    { 
        try { 
            // creating and initializing  MessageFormat 
            MessageFormat mf 
                = new MessageFormat("{0, number, #}, {2, number, #.#}, {1, number, #.##}"); 
            ; 
  
            // creating and initializing String source 
            String str = "10.456, 20.325, 30.444"; 
  
            // parsing the string 
            // accoridng to MessageFormat 
            // using parse() method 
            Object[] hash = mf.parse(str); 
  
            // display the result 
            System.out.println("Parsed value are:"); 
            for (int i = 0; i < hash.length; i++) 
                System.out.println(hash[i]); 
        } 
        catch (ParseException e) { 
            System.out.println("\nString is Null"); 
            System.out.println("Exception thrown:" + e); 
        } 
    } 
}
输出:
Parsed value are:
10.456
30.444
20.325

范例2:

// Java program to demonstrate 
// parse() method 
  
import java.text.*; 
import java.util.*; 
import java.io.*; 
  
public class GFG { 
    public static void main(String[] argv) 
    { 
        try { 
            // creating and initializing  MessageFormat 
            MessageFormat mf 
                = new MessageFormat("{0, date}, {2, time}, {1, number}"); 
  
            // creating and initializing String source 
            String str = "10, 20, 30"; 
  
            // parsing the string 
            // accoridng to MessageFormat 
            // using parse() method 
            Object[] hash = mf.parse(str); 
  
            // display the result 
            System.out.println("Parsed value are:"); 
            for (int i = 0; i < hash.length; i++) 
                System.out.println(hash[i]); 
        } 
        catch (ParseException e) { 
            System.out.println("String is Null"); 
            System.out.println("Exception thrown:" + e); 
        } 
    } 
}
输出:
String is Null
Exception thrown:java.text.ParseException:MessageFormat parse error!

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




相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 MessageFormat parse() method in Java with Example : Set – 1。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。