Java Reference
In-Depth Information
action corresponding to the first true Boolean expression is executed. The final else
is optional. If there is a final else and all the Boolean expressions are false , the final
action is executed. If there is no final else and all the Boolean expressions are false ,
then no action is taken. An example of a multiway if-else statement is given in the
following Programming Example.
Multiway if-else Statement
SYNTAX
if ( Boolean_Expression_1 )
Statement_1
else if ( Boolean_Expression_2 )
Statement_2
.
.
.
else if ( Boolean_Expression_n )
Statement_n
else
Statement_For_All_Other_Possibilities
EXAMPLE
if (numberOfPeople < 50)
System.out.println("Less than 50 people");
else if (numberOfPeople < 100)
System.out.println("At least 50 and less than 100 people");
else if (numberOfPeople < 200)
System.out.println("At least 100 and less than 200 people");
else
System.out.println("At least 200 people");
The Boolean expressions are checked in order until the first true Boolean expression is
encountered, and then the corresponding statement is executed. If none of the Boolean
expressions is true , then the Statement_For_All_Other_Possibilities is executed.
EXAMPLE: State Income Tax
Display 3.1 contains a program that uses a multiway if-else statement to compute
state income tax. This state computes tax according to the following rate schedule:
1. No tax is paid on the fi rst $15,000 of net income.
2. A tax of 5% is assessed on each dollar of net income from $15,001 to $30,000.
3. A tax of 10% is assessed on each dollar of net income over $30,000.
(continued)
 
Search WWH ::




Custom Search