Java Reference
In-Depth Information
process “unexpected” data? This can turn out to be very dicult to assert for
moderate-size programs. For example, consider the quadratic equation solver:
Program 2.11
Quadratic equation solver
import
java . util .
∗
;
class
QuadraticEquationScanner
{
public static void
main( String [ ] arg )
double
a,b,c;
// choose a=1, b=1, c=1
Scanner input=
new
Scanner(System . in ) ; input . useLocale (Locale .
US) ;
a=input . nextDouble () ;
b=input . nextDouble () ;
c=input . nextDouble () ;
double
delta=b
∗
b
−
4.0
∗
a
∗
c;
double
root1 , root2 ;
// BEWARE: potentially Not a Number (NaN) for neg.
discriminant!
root1= (
−
b
−
Math. sqrt(delta))/(2.0
∗
a);
root2= (
−
b+Math. sqrt(delta))/(2.0
∗
a);
System . out . println (
"root1="
+root1+
" root2="
+root2) ;
}
}
The problem with that program is that we may compute roots of negative
numbers. Although mathematically this makes sense with imaginary numbers
C
, this is not the case for the function
Math.sqrt()
. The function returns a
special number called
NaN
(standing for Not a Number) so that the two roots
may be equal to
NaN
. It is much better to avoid that case by ensuring with a
condition that
delta
is greater or equal to zero:
if
(delta
>
=0.0d)
root1= (
−
b
−
Math.sqrt(delta))/(2.0
∗
a);
root2= (
−
b+Math.sqrt(delta))/(2.0
∗
a);
System . out . println (
"root1="
+root1+
" root2="
+root2) ;
else
{
System . out . println (
"Imaginary roots!"
);
}
The rule of thumb is to write easy-to-read code and adopt conventions once and
for all. For example, always put a semi-colon at the end of instructions, even
if it is not required (atomic blocks). Always indent the source code to better
visualize nested structures with braces
{}
. Take particular care of equality test
==
with assignment equal symbol
=
(type checking helps find some anomalous
situations but not all of them).
Finally, let us insist that even if we considered all possible input cases and
wrote our codes keeping in mind that they must also be human-readable, it
Search WWH ::
Custom Search