2018年3月2日 星期五

if-else Branching

The basic format of an if statement is as follows:

if (booleanExpression) {
    System.out.println("Inside if statement");
}

The expression in parentheses must evaluate to (a boolean) true or false. Typically you're testing something to see if it's true, and then running a code block (one or more statements) if it is true, and (optionally) another block of code if it isn't. The following code demonstrates a legal if-else statement:

if (x > 3) {
    System.out.println("x is greater than 3");
} else {
    System.out.println("x is not greater than 3");
}

The else block is optional, so you can also use the following:

if (x > 3) {
    y = 2;
}
z += 8;
a = y + x;

The preceding code will assign 2 to y if the test succeeds (meaning x really is greater than 3), but the other two lines will execute regardless. Even the curly braces are optional if you have only one statement to execute within the body of the conditional block. The following code example is legal (although not recommended for readability):

if (x > 3) // bad practice, but seen on the exam
    y = 2;
z += 8;
a = y + x;

Sun considers it good practice to enclose blocks within curly braces, even if there's only one statement in the block. Be careful with code like the above, because you might think it should read as,

"If x is greater than 3, then set y to 2, z to z + 8, and a to y + x."

But the last two lines are going to execute no matter what! They aren't part of the conditional flow. You might find it even more misleading if the code were indented as follows:

if (x > 3)
y = 2;
z += 8;
a = y + x;

You might have a need to nest if-else statements (although, again, it's not recommended for readability, so nested if tests should be kept to a minimum). You can set up an if-else statement to test for multiple conditions. The following example uses two conditions so that if the first test fails, we want to perform a second test before deciding what to do:

if (price < 300) {
    buyProduct();
} else {
    if (price < 400) {
        getApproval();
    }
    else {
        dontBuyProduct();
    }
}

This brings up the other if-else construct, the if, else if, else. The preceding code could (and should) be rewritten:

if (price < 300) {
    buyProduct();
} else if (price < 400) {
    getApproval () ;
} else {
    dontBuyProduct();
}

There are a couple of rules for using else and else if:
  • You can have zero or one else for a given if, and it must come after any else ifs.
  • You can have zero to many else ifs for a given if and they must come before the (optional) else.
  • Once an else if succeeds, none of the remaining else ifs or elses will be tested.

The following example shows code that is horribly formatted for the real world. As you've probably guessed, it's fairly likely that you'll encounter formatting like this on the exam. In any case, the code demonstrates the use of multiple else ifs:

int x = 1;
if ( x == 3 ) { }
else if (x < 4) {System.out.println("<4"); }
else if (x < 2) {System.out.println("<2"); }
else { System.out.println("else"); }

It produces the output:

<4

(Notice that even though the second else if is true, it is never reached.) Sometimes you can have a problem figuring out which if your else should pair with, as follows:

if (exam. done())
    if (exam.getScore() < 0.61)
        System.out.println("Try again.");
    // Which if does this belong to?
    else
        System.out.println("Java master!");

We intentionally left out the indenting in this piece of code so it doesn't give clues as to which if statement the else belongs to. Did you figure it out? Java law decrees that an else clause belongs to the innermost if statement to which it might possibly belong (in other words, the closest preceding if that doesn't have an else). In the case of the preceding example, the else belongs to the second if statement in the listing. With proper indenting, it would look like this:

if (exam. done())
    if (exam.getScore() < 0.61)
    System.out.println("Try again.");
    // Which if does this belong to?
    else
        System.out.println("Java master!");

Following our coding conventions by using curly braces, it would be even easier to read:

if (exam.done()) {
    if (exam.getScore() < 0.61) {
        System.out.println("Try again.");
    // Which if does this belong to?
    } else {
        System.out.println("Java master!");
    }
}

Don't get your hopes up about the exam questions being all nice and indented properly. Some exam takers even have a slogan for the way questions are presented on the exam: anything that can be made more confusing, will be.

Be prepared for questions that not only fail to indent nicely, but intentionally indent in a misleading way: Pay close attention for misdirection like the following:

if (exam. done())
    if (exam.getScore() < 0.61)
        System.out.println("Try again.");
else
    System.out.println("Java master!");    // Hmmmmm ... now where does
                        // it belong?

Of course, the preceding code is exactly the same as the previous two examples, except for the way it looks.

Given:

1. public class Test{
2.     public static void main(String[] args){
3.         int x = 5;
4.         boolean b1 = true;
5.         boolean b2 = false;
6.
7.         if((x==4) && !b2)
8.             System.out.print("1 ");
9.             System.out.print("2 ");
10.         if((b2=true) && b1)
11.             System.out.print("3 ");
12.     }
13. }

What is the result?

A. 2
B. 3
C. 1 2
D. 2 3
E. 1 2 3
F. Compilation fails.
G. An exception is thrown at runtime.


Given:

22. public void go(){
23.     String o = "";
24.     z:
25.     for(int x=0; x<3; x++){
26.         for(int y=0; y<2; y++){
27.             if(x == 1) break;
28.             if(x==2 && y==1) break z;
29.             o = o + x + y;
30.         }
31.     }
32.     System.out.println(o);
33. }

What is the result when the go() method is invoked?

A. 00
B. 0001
C. 000120
D. 00012021
E. Compilation fails.
F. An exception is thrown at runtime.

沒有留言:

張貼留言