Java Reference
In-Depth Information
Nesting if-then Statements
Control structures, such as if-then statements, can also be nested. This means that one if-then state-
ment is inside another if-then statement, as if the outer statement formed a nest for the inner state-
ment. This concept looks something like the following:
if (accountBalance > 0) {
System.out.println("Safe balance.");
if (accountDays > 90) {
System.out.println(savingsAccountOffer);
}
} else {
System.out.println("ALERT: Negative balance!");
}
This is an example of nested if-then statements because the if (accountDays > 90) statement is
nested inside the if (accountBalance > 0) statement. This program will first check if the account
balance is greater than zero. If it is greater than zero, it will print a safe balance notification and then
check if the account has been active more than 90 days. If this is also true, then an offer to open a sav-
ings account will also be printed. However, if the account balance is not greater than zero, the negative
balance alert will be printed and the accountDays variable will never be evaluated.
This could also be accomplished using the Boolean operators discussed earlier in this chapter. That
approach would look like this:
if (accountBalance > 0 && accountDays <= 90) {
System.out.println("Safe balance.");
} else if (accountBalance > 0 && accountDays > 90) {
System.out.println("Safe balance.");
System.out.println(savingsAccountOffer);
} else {
System.out.println("ALERT: Negative balance!");
}
You will notice that the " Safe balance" print command is repeated for the first two if-then state-
ments. That means if you want to adjust the statement that is printed whenever a balance is over
zero, or if you want to add and change any other actions to perform when the balance is greater
than zero, you would have to make those changes in both places.
If you have more than two conditions to evaluate, you can nest deeper than two levels. To maintain
readability, the closing bracket (}) should be lined up vertically with the if keyword it closes.
if (accountBalance > 0) {
System.out.println("Safe balance.");
if (accountDays > 90) {
System.out.println(savingsAccountOffer);
if (creditAccounts > 1) {
balanceTransferPossible = true;
} else {
sendCreditApplication();
}
}
 
Search WWH ::




Custom Search