Java Reference
In-Depth Information
12. System.out.println(fr.parse(s));
13. }catch(ParseException e) {
14. e.printStackTrace();
15. }
The string being parsed is
”123,45”
. In the U.S. locale, the comma is treated as a visual
format and is ignored, so the resulting number is the integer
12345
. In the France locale, the
comma is a decimal separator, so the resulting number is the double
123.45
. The output of
the code is
12345
123.45
The
parse
method only parses the beginning of a string. After it reaches a character that
cannot be parsed, the parsing stops and the value is returned. See if you can determine the
output of the following statements:
NumberFormat nf = NumberFormat.getInstance();
try {
String one = “456abc”;
String two = “-2.5165e10”;
String three = “x85.3”;
System.out.println(nf.parse(one));
System.out.println(nf.parse(two));
System.out.println(nf.parse(three));
}catch(ParseException e) {
e.printStackTrace();
}
The
NumberFormat
object uses the default locale to parse
”456abc”
. When the
'a'
char-
acter is reached, the parsing stops and
456
is returned. Similarly, the
String two
is parsed
into
-2.5165
. Parsing
”x85.3”
throws a
ParseException
because the beginning of the
string cannot be parsed. The output of the code is
456
-2.5165
java.text.ParseException: Unparseable number: “x85.3”
I do not think the exam will test your knowledge of such details about the
parse
method and the point at which parsing fails, but it is a good trait to
understand. Instead, expect a question that successfully
parses
a string
to a number.
Search WWH ::
Custom Search