Java Reference
In-Depth Information
andom number generators are good enough for most purposes, so we use them. Java provides
one random generator in the base library java.lang.Math , and several others; we'll examine
these in Generating Random Numbers .
The class java.lang.Math contains an entire “math library” in one class, including trigono-
metry, conversions (including degrees to radians and back), rounding, truncating, square
root, minimum, and maximum. It's all there. Check the javadoc for java.lang.Math .
The package java.Math contains support for “big numbers”—those larger than the normal
built-in long integers, for example. See Handling Very Large Numbers .
Java works hard to ensure that your programs are reliable. The usual ways you'd notice this
are in the common requirement to catch potential exceptions—all through the Java API—and
in the need to “cast” or convert when storing a value that might or might not fit into the vari-
able you're trying to store it in. I'll show examples of these.
Overall, Java's handling of numeric data fits well with the ideals of portability, reliability,
and ease of programming.
See Also
The Java Language Specification. The javadoc page for java.lang.Math .
Checking Whether a String Is a Valid Number
Problem
You need to check whether a given string contains a valid number, and, if so, convert it to
binary (internal) form.
Solution
To accomplish this, use the appropriate wrapper class's conversion routine and catch the
NumberFormatException . This code converts a string to a double :
public
public static
void main ( String [] argv ) {
String aNumber = argv [ 0 ];
static void
// not argv[1]
double
double result ;
Search WWH ::




Custom Search