Java Reference
In-Depth Information
Nested Statements
As you have seen, if-else statements and if statements contain smaller statements
within them. Thus far, we have used compound statements and simple statements,
such as assignment statements, as these smaller substatements, but there are other pos-
sibilities. In fact, any statement at all can be used as a subpart of an if-else statement
or other statement that has one or more statements within it.
When nesting statements, you normally indent each level of nested substatements,
although there are some special situations (such as a multiway if-else statement)
where this rule is not followed.
indenting
Self-Test Exercises
1. Write an if-else statement that outputs the word "High" if the value of the vari-
able score is greater than 100 and outputs "Low" if the value of score is at most
100. The variable score is of type int .
2. Suppose savings and expenses are variables of type double that have been given
values. Write an if-else statement that outputs the word "Solvent" , decreases
the value of savings by the value of expenses , and sets the value of expenses to
zero, provided that savings is larger than expenses . If, however, savings is less
than or equal to expenses , the if-else statement should simply output the word
"Bankrupt" without changing the value of any variables.
3. Suppose number is a variable of type int . Write an if-else statement that outputs
the word "Positive" if the value of the variable number is greater than 0 and out-
puts the words "Not positive" if the value of number is less than or equal to 0.
4. Suppose salary and deductions are variables of type double that have been given
values. Write an if-else statement that outputs the word "Crazy" if salary is
less than deductions ; otherwise, it should output "OK" and set the variable net
equal to salary minus deductions .
Multiway if-else Statement
The multiway if-else statement is not really a different kind of Java statement. It is
simply ordinary if-else statements nested inside of if-else statements, but it is
thought of as a different kind of statement and is indented differently from other
nested statements so as to reflect this thinking.
The syntax for a multiway if-else statement and a simple example are given in the
box entitled “Multiway if-else Statement.” Note that the Boolean expressions are
aligned with one another, and their corresponding actions are also aligned with one
another. This makes it easy to see the correspondence between Boolean expressions
and actions. The Boolean expressions are evaluated in order until a true Boolean
expression is found. At that point, the evaluation of Boolean expressions stops, and the
multiway
if-else
statement
Search WWH ::




Custom Search