Java Reference
In-Depth Information
public class
FloatingPointFormat
extends
Format {
public
String getName() {
return
"float"; }
public
String toString(Rational number) {
double
value
#
number.numerator / number.denominator;
if
(value
##
0.0){
return
"0.0*10^1";
}
else
{
double
exponent
#
Math.floor(Math.log
(Math.abs(value))/Math.log(10));
double
mantissa
#
Math.abs(value)
/ Math.pow(10,exponent);
String result
#
"";
result
#
Double.toString(mantissa)
!
"*10^"
!
Double.toString(exponent);
if
(value < 0){
result
#
"-"
!
result;
}
return
result;
}
}
public
Rational parse(String number)
throws
FormatException {
int
indexMul
#
number.indexOf('*');
int
indexPow
#
number.indexOf('^');
if
(indexMul <
#
0
||
indexPow <
#
0) {
throw new
FormatException("Error!
Not a floating point format");
}
double
mantissa
#
Double.parseDouble
(number.substring(0,indexMul));
double
power
#
Double.parseDouble
(number.substring(indexPow
!
1));
double
value
#
mantissa*Math.pow(10,power);
return new
Rational(value);
}
}
Class
Calculator
implements the basic functionalities of the calculator.
The two operands are initialized with the default value of
Rational
. The
format is initialized as fixed point.
Method
addOperand()
accepts a new operand, parses it and stores it as the
second operand, while the previous value of the second operand is copied to
the first operand. The exception thrown by the
parse()
method of class
Format
is simply propagated. In fact this method is declared to throw the
Format
Exception
. The order of the statements in this method is arranged to preserve
the coherence of the calculator if an exception is thrown: the
operand_1
attribute is overwritten only if the parse is successful (see Sidebar 6.3).