Java Reference

In-Depth Information

public
Rational parse(String number) {

return new
Rational(Double.parseDouble(number));

}

}

The
FractionalFormat
class represents the fractional format. The
toString()
is

straightforward since the internal representation format is already expressed

in terms of numerator and denominator. The
parse()
method first identifies

numerator and denominator, then uses the standard
Double.parseDouble()

method. If the “

” is not found, it means that the format of the number is not

correct, therefore an exception is thrown.

public class
FractionalFormat
extends
Format {

public
String getName() {
return
"fract"; }

String toString(Rational number) {

return
Double.toString(number.numerator)
!

"/"
!
Double.toString(number.denominator);

}

Rational parse(String number)
throws
FormatException {

int
index
#
number.indexOf('/');

if
(index >
#
0)

return new
Rational(Double.parseDouble(

number.substring(0, index).trim()),

Double.parseDouble(number.substring

(index
!
1).trim()));

else
{

throw new
FormatException("Error!

Not a rational format");

}

}

}

The
FloatingPointFormat
class, which represents the floating point format,

is the most complex of the three. The
toString()
method calculates the

number as a double performing the division between numerator and

denominator, then the simple case of 0 is skipped. The exponent of the

number is the logarithm in base 10 of the number, while the mantissa equals

the number divided by 10 raised to the exponent. The
parse()
method first

identifies mantissa and exponent by means of the characters “

” and “
^
”. If

these characters are not found the format of the number is not correct,

therefore an exception is thrown. Otherwise the value is computed

according to Equation 6.5.

Since the mathematical package only provides the natural logarithm

method we have to use Equation 6.8 to compute the base 10 logarithm:

(

log
B

x

log
A

x

=

A

log
B

Equation 6.8
Equivalence of logarithms