O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Parsing Input

Number formats also handle input. When used for input, a number format converts a string in the appropriate format to a binary number, achieving more flexible conversions than you can get with the methods in the type wrapper classes (like Integer.parseInt()). For instance, a percent format parse() method can interpret 57% as 0.57 instead of 57. A currency format can read (12.45) as -12.45.

There are three parse() methods in the NumberFormat class. All do roughly the same thing:

public Number parse(String text) throws ParseException
public abstract Number parse(String text, ParsePosition parsePosition)
public final Object parseObject(String source, ParsePosition parsePosition)

The first parse() method attempts to parse a number from the given text. If the text represents an integer, it’s returned as an instance of java.lang.Long. Otherwise, it’s returned as an instance of java.lang.Double. If a string contains multiple numbers, only the first one is returned. For instance, if you parse “32 meters” you’ll get the number 32 back. Java throws away everything after the number finishes. If the text cannot be interpreted as a number in the given format, a ParseException is thrown. The second parse() method specifies where in the text parsing starts. The position is given by a ParsePosition object. This is a little more complicated than using a simple int but does have the advantage of allowing one to read successive numbers from the same string. The third parse() method merely ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required