Java Reference
In-Depth Information
The correct code to print Passing or Failing , depending on the value of score , is:
if (score >= 60)
System.out.println("Passing");
else
System.out.println("Failing");
Compound (Block of) Statements
The if and if ... else structures select only one statement at a time. Suppose, however,
that you want to execute more than one statement if the logical expression in an if
or if ... else statement evaluates to true . To permit more complex statements, Java
provides a structure called a compound statement or a block of statements. A
compound statement takes the following form:
4
{
statement1
statement2
.
.
.
statementn
}
That is, a compound statement or block consists of a sequence of statements enclosed in
braces. In an if or if ... else structure, a compound statement functions as if it were a
single statement. Thus, instead of having a simple two-way selection similar to the
following code:
if (age > 18)
System.out.println("Eligible to vote.");
else
System.out.println("Not eligible to vote.");
you could include compound statements, similar to the following code:
if (age > 18)
{
System.out.println("Eligible to vote.");
System.out.println("No longer a minor.");
}
else
{
System.out.println("Not eligible to vote.");
System.out.println("Still a minor.");
}
The compound statement is useful and will be used in most of the ensuing structured
statements in this chapter.
 
 
Search WWH ::




Custom Search