Chapter 5: Controlling Program Flow with Decision-Making Statements (Make web site)

Chapter 5: Controlling Program Flow with Decision-Making Statements 107 Brace yourself The ifstatement in Listing 5-1 has two halves a top half and a bottom half. I have names for these two parts of an ifstatement. I call them the if part (the top half) and the else part (the bottom half). The ifpart in Listing 5-1 seems to have more than one statement in it. I make this happen by enclosing the three statements of the ifpart in a pair of curly braces. When I do this, I form a block. A block is a bunch of statements scrunched together by a pair of curly braces. With this block, three calls to printlnare tucked away safely inside the if part. With the curly braces, the rows of asterisks and the words You winare displayed only when the user s guess is correct. This business with blocks and curly braces applies to the elsepart as well. In Listing 5-1, whenever inputNumberdoesn t equal randomNumber, the computer executes three print/printlncalls. To convince the computer that all three of these calls are inside the elseclause, I put these calls into a block. That is, I enclose these three calls in a pair of curly braces. Strictly speaking, Listing 5-1 has only one statement between the ifand the elsestatements and only one statement after the elsestatement. The trick is that when you place a bunch of statements inside curly braces, you get a block; and a block behaves, in all respects, like a single statement. In fact, the official Java documentation lists blocks as one of the many kinds of statements. So, in Listing 5-1, the block that prints You winand asterisks is a single statement. It s a statement that has, within it, three smaller statements. Indenting if statements in your code Notice how, in Listing 5-1, the printand printlncalls inside the ifstatement are indented. (This includes both the You winand You losestatements. The printand printlncalls that come after the word else are still part of the ifstatement.) Strictly speaking, you don t have to indent the statements that are inside an ifstatement. For all the compiler cares, you can write your whole program on a single line or place all your statements in an artful, misshapen zigzag. The problem is that if you don t indent your statements in some logical fashion, neither you nor anyone else can make sense of your code. In Listing 5-1, the indenting of the printand println statements helps your eye (and brain) see quickly that these statements are subordinate to the overall if/elseflow. In a small program, unindented or poorly indented code is barely tolerable. But in a complicated program, indentation that doesn t follow a neat, logical pattern is a big, ugly nightmare.
Need a managed web hosting provider to help maintain your website? Our web hosting service is the preferred choice of thousands of demanding customers.

Leave a Reply