(^130) | Arithmetic Expressions
Converting Strings to Numeric Values
Many of the problems that we use computers to solve involve the entry of numerical
data—that is, values of the typesint,long,float, anddouble.ABufferedReaderobject enables
us to enter aString. How, then, do we input a number? The answer is that we can’t—at least
not directly. Java provides only for the input of strings. We must enter a number as a string
and then convert the string into one of the numeric types using methods from Java’s
library.
Java’s standard library includes a set of classes that correspond to the built-in numeric
types. These classes provide methods and constants that are useful in working with the
numeric types. Like the Mathclass, they are auto-
matically imported to every Java class. Table 3.2
lists these predefined classes and the built-in type
to which each one corresponds.
As you can see, the general rule is that the
class name is the same as the name of the built-
in type except that its first letter is capitalized.
The lone exception is that the class correspon-
ding to intis called Integer.
Among the methods associated with each
of these classes is one that takes a string as its
argument and returns a value of the correspon-
ding type. Table 3.3 shows the relevant methods.
For example, we can write
number = Double.parseDouble("–435.82E27");
to convert"–435.82E27"into a value of typedouble
and store it innumber. Of course, what we really
want to do is convert an input string into a num-
ber. We can replace the string"–435.82E27"in the
preceding statement with a call to thereadLinemethod associated with aBufferedReader:
number = Double.parseDouble(in.readLine());
Let’s look at an example of inputting an integer value:
int intNumber;
intNumber = Integer.parseInt(in.readLine());
We now have a single statement that reads a numerical value from the screen. What if
the user types something other than a number? At this point in our knowledge of Java, the
result is that the application halts and displays a message such as “Number Format Error.”
In Chapter 9, we will see how an application can catch such an error (another example of an
exception) and respond to it without stopping.
Built-in Type Object Type
int Integer
long Long
float Float
double Double
Table 3.2 Predefined Classes Corresponding to Built-in Numeric Types
Object Type Method Argument Returns
Integer parseInt String int
Long parseLong String long
Float parseFloat String float
Double parseDouble String double
Table 3.3 String-to-Numeric Type Conversion Methods
T
E
A
M
F
L
Y
Team-Fly®