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.
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.Output
As you can see, the output has leading spaces. If we change to:
Then it all works.
Output