• Tidak ada hasil yang ditemukan

PROGRAMMING TIP Alphabetic Order

To see whether two strings of letters are in alphabetic order, you must ensure that all the letters have the same case before using the method compareTo to compare the strings. You can use either of the String methods toUpperCase

or toLowerCase to accomplish this. If you were to omit this step, using

compareTo would compare lexicographic order instead of alphabetic order.

SELF-TEST QUESTIONS

1. Suppose goals is a variable of type int. Write an if-else statement that displays the word Wow if the value of the variable goals is greater than 10 and displays the words Oh Well if the value of goals is at most 10.

2. Suppose goals and errors are variables of type int. Write an if-else

statement that displays the word Wow if the value of the variable goals is greater than 10 and the value of errors is 0. Otherwise, the if-else

statement should display the words Oh Well.

3. Suppose salary and deductions are variables of type double that have been given values. Write an if-else statement that displays OK and sets the variable net equal to salary minus deductions, provided that salary

is at least as large as deductions. If, however, salary is less than

deductions, the if-else statement should simply display the words No Way but not change the value of any variables.

4. Suppose speed and visibility are variables of type int. Write an if

statement that sets the variable speed equal to 25 and displays the word

Caution, provided the value of speed is greater than 25 and the value of

visibility is under 20. There is no else part.

5. Suppose salary and bonus are variables of type double. Write an if-else

statement that displays the word OK provided that either salary is greater than or equal to MIN_SALARY or bonus is greater than or equal to MIN_

BONUS. Otherwise, it should display Toolow. MIN_SALARY and MIN_BONUS

are named constants.

6. Assume that nextWord is a String variable that has been given a value consisting entirely of letters. Write some Java code that displays the message First half of the alphabet, provided that nextWord precedes the letter N in alphabetic ordering. If nextWord does not precede N in alphabetic ordering, your code should display Second half of the alphabet. Be careful when you represent the letter N. You will need a

String value, as opposed to a char value.

7. Suppose x1 and x2 are two variables that have been given values. How do you test whether the values are equal when the variables are of type int? How about when the variables are of type String?

Nested

if-else

Statements

An if-else statement can contain any sort of statements within it. In particular, you can nest one if-else statement within another if-else

statement, as illustrated by the following:

if (balance >= 0) if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance) / 12;

else

System.out.println("Cannot have a negative interest.");

else

balance = balance − OVERDRAWN_PENALTY;

If the value of balance is greater than or equal to zero, the entire following

if-else statement is executed:

if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance) / 12;

else

System.out.println("Cannot have a negative interest.");

The nested statements can be made clearer by adding braces, as follows:

if (balance >= 0) {

if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance)/12;

else

System.out.println("Cannot have a negative interest.");

} else

balance = balance − OVERDRAWN_PENALTY;

In this case, the braces are an aid to clarity but are not, strictly speaking, needed.

Any action within an if-else statement can be nested in another if-else

statement

In other cases, braces are needed. If we omit an else, for example, things get a bit trickier. The following two statements differ in appearance only in that one has a pair of braces, but they do not have the same meaning:

//First Version − Braces if (balance >= 0)

{

if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance)/12;

} else

balance = balance − OVERDRAWN_PENALTY;

//Second Version - No Braces if (balance >= 0)

if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance)/12;

else

balance = balance − OVERDRAWN_PENALTY;

In an if-else statement, each else is paired with the nearest preceding unmatched if. The second version—without braces—pairs the else with the second if, despite the misleading indentation. Thus, the meaning is

//Equivalent to Second Version if (balance >= 0)

{

if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance)/12;

else

balance = balance OVERDRAWN_PENALTY;

}

To clarify the difference a bit more, consider what happens when balance is greater than or equal to zero. In the first version, the following action occurs:

if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance)/12;

If balance is not greater than or equal to zero in the first version, the following action is taken instead:

balance = balance − OVERDRAWN_PENALTY;

In the second version, if balance is greater than or equal to zero, the following entire if-else statement is executed:

if (INTEREST_RATE >= 0)

balance = balance + (INTEREST_RATE * balance)/12;

else

balance = balance − OVERDRAWN_PENALTY;

If balance is not greater than or equal to zero in the second version, no action is taken.

PROGRAMMING TIP

Matching else and if

In an if-else statement, each else is paired with the nearest preceding unmatched if. Use indentation that is consistent with the meaning of the statement to clarify your intent. But remember that the compiler ignores indentation. When in doubt, use braces to make the statement’s meaning

explicit. ■

Multibranch

if-else

Statements

If you have the ability to branch two ways, you have the ability to branch four ways. Just branch two ways and have each of those two outcomes branch two ways. Using this trick, you can nest if-else statements to produce multiway branches that result in any number of possibilities. Programmers have a standard way of doing this. In fact, it has become so standard that it is treated as if it were a new kind of branching statement rather than just several nested

if-else statements. Let’s start with an example.

Suppose balance is a variable that holds your checking account balance, and you want to know whether your balance is positive, negative (overdrawn), or zero. To avoid any questions about accuracy, let’s say balance is the number of dollars in your account, with the cents ignored. That is, let’s assume that

balance is of type int. To find out if your balance is positive, negative, or zero, you could use the following nested if-else statement:

if (balance > 0)

System.out.println("Positive balance");

else

if (balance < 0)

System.out.println("Negative balance");

else

if (balance == 0)

System.out.println("Zero balance");

An equivalent, clearer, and preferred way to write this statement is as follows:

if (balance > 0)

System.out.println("Positive balance");

else if (balance < 0)

System.out.println("Negative balance");

else if (balance == 0)

System.out.println("Zero balance");

We call this form a multibranch if-else statement. This statement is really an ordinary nested if-else statement, but the way we have indented it reflects the way we think about multibranch if-else statements.

A multibranch if-else statement offers a choice among several actions

When a multibranch if-else statement is executed, the computer tests the boolean expressions one after the other, starting from the top. When the first true boolean expression is found, the statement following that true boolean expression is executed. For example, if balance is greater than zero, the preceding code will display Positive balance. If balance is less than zero, then Negative balance is displayed. Finally, if balance is equal to zero, the code displays Zero balance. Exactly one of the three possible outputs will be produced, depending on the value of the variable balance.

In this first example, we had three possibilities, but you can have any number of possibilities; just add more else-if parts. Also, the possibilities in this example were mutually exclusive. That is, only one possibility is true at a given time. However, you can use any boolean expressions, even if they are not mutually exclusive. If more than one boolean expression is true, only the action associated with the first true boolean expression is executed. A multibranch if-else statement never performs more than one action.

If none of the boolean expressions is true, nothing happens. However, it is a good practice to add an else clause—without any if—at the end that will be executed in case none of the boolean expressions is true. In fact, we can rewrite our original checking-account example in this way. We know that, if balance

is neither positive nor negative, it must be zero. So we do not need the last test:

if (balance == 0)

Thus, our previous multibranch if-else statement is equivalent to the following one:

if (balance > 0)

System.out.println("Positive balance");

else if (balance < 0)

System.out.println("Negative balance");

else

System.out.println("Zero balance");

RECAP Multibranch if-else Statement SYNTAX

if (Boolean_Expression_1) Action_1

else if (Boolean_Expression_2) Action_2 .

. . .

else if (Boolean_Expression_n) Action_n

else

Default_Action

(continued)

Only one action occurs

Write a final else clause

VideoNote

Using multibranch if-else statements