Java Reference
In-Depth Information
String inputMsg = " 003 ";
int x = 0;
// Try to convert String to integer. Catch any NumberFormat exception errors.
try { x = Integer.parseInt (inputMsg.trim());
}
catch (NumberFormatException e) {
...
x = 0;
}
This code sample first removes any trailing or leading spaces from
inputMsg
(using
its
trim()
method), and then passes that result
String
to the
parseInt()
method in
the
Integer
class. (Notice that no
Integer
object was created before
parseInt()
was
called; this method is a static method, and so can be accessed without first creating an
Integer
object.) If any nonnumeric characters are discovered in
inputMsg
, the
Number-
FormatException
exception will be thrown. It is best if this code block catches the ex-
ception and performs any appropriate action (such as setting x to zero).
The
Double
numeric class wrapper does not have a similar method. Instead, you
have to use the
doubleValue()
method to return a numeric of type
double
and then
pass the returned
String
to one of the constructors for the
Double
class. The (rather
gruesome) code looks like this:
String inputMsg = " 003 ";
double d = 0;
// Try to convert String to a double using the doubleValue() String method.
// Catch any NumberFormat exception errors.
try { d = new Double (inputMsg.trim()).doubleValue();
}
catch (NumberFormatException e) {
...
d = 0;
}
Java does provide a slightly more useful and consistent mechanism to convert
String
s into numerics: the
DecimalFormat
class and its
parse()
method. This
method accepts a
String
parameter and returns an abstract class of type
Number
(that is, either a
Long
or a
Double
object). The
Number
class, in turn, does implement
the
doubleValue()
method, so you can always get a numeric double value from it if
you would like: