Java Reference
In-Depth Information
if (booleanExpression)
{BlockA}
Conditional structures allow one to perform various status checks on variables
to branch to the appropriate subsequent block of instructions. Let us revisit
the quadratic equation solver:
Program 2.1 Quadratic equation solver with user input
import java . util . ;
class QuadraticEquationRevisited
{ public static void main( String [ ] arg )
Scanner keyboard= new Scanner(System . in ) ;
System . out . print ( "Enter a,b,c of equation ax^2+bx+c=0:" );
double a=keyboard . nextDouble () ;
double b=keyboard . nextDouble () ;
double c=keyboard . nextDouble () ;
double delta=b
b
4.0
a
c;
double root1 , root2 ;
if (delta > =0)
root1= ( b Math.sqrt(delta))/(2.0 a);
root2= ( b+Math.sqrt(delta))/(2.0 a);
System . out . println ( "Two real roots:" +root1+ "" +root2) ;
else
{ System . out . println ( "No real roots" ); }
}
}
In this example, we asserted that the computations of the roots root1 and
root2 are possible using the fact that the discriminant delta>=0 in the block
of instructions executed when expression delta>=0 is true . Running this
program twice with respective user keyboard input 123 and -1 2 3 yields
the following session:
Enter a,b,c of equation ax^2+bx+c=0:1 2 3
No real roots
Enter a,b,c of equation ax^2+bx+c=0:-1 2 3
Two real roots:3.0 -1.0
In the if else conditionals, the boolean expressions used to select the
appropriate branchings are also called boolean predicates .
 
Search WWH ::




Custom Search