unable to parse text using MessageFormat

599 views Asked by At

I am attempting to use MessageFormat class to parse a message. But I get "MessageFormat parse error!". I got this code from internet. Here is the link:

package myy.test;
import java.text.MessageFormat;
import java.text.ParseException;

public class TestParse {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    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"; 
        System.out.println(str); 
        // 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); 
    } 

}
}

I get the following output in the console.

10.456, 20.325, 30.444

String is Null
Exception thrown : java.text.ParseException: MessageFormat parse error!

Why do I get this error and how do I resolve it? Thanks.

2

There are 2 answers

0
Andreas On

As always when encountering parsing issues, try doing the reverse operation to see when input the parse is expecting. This is a general guideline that applies to XML, JSON, Dates, and to MessageFormat.

MessageFormat mf 
    = new MessageFormat("{0, number, #}, {2, number, #.#}, {1, number, #.##}"); 
; 

System.out.println(mf.format(new Integer[] { 10456, 30444, 20325 }));

Output

 10456,  20325,  30444

As you can see, the output has leading spaces. If we change to:

String str = " 10.456,  20.325,  30.444"; 

Then it all works.

Output

 10.456,  20.325,  30.444
Parsed value are :
10.456
30.444
20.325
0
xingxing On

I changed the parameters in the constructor to this

MessageFormat mf = new MessageFormat("{0,number,#,###.##}, {2,number,#,###.##}, {1,number,#,###.##}");

Consolo output is like this:

10.456, 20.325, 30.444
Parsed value are :
10.456
30.444
20.325