Chapter 5: Controlling Program Flow with Decision-Making Statements (Managed web hosting)
Chapter 5: Controlling Program Flow with Decision-Making Statements 119 Figure 5-8 shows two runs of the program in Listing 5-6. (The overall idea behind the program is illustrated in Figure 5-9.) First, the user types a number, like the number 2. Then, execution of the program reaches the top of the switchstatement. The computer checks the value of the versevariable. When the computer determines that the versevariable s value is 2, the computer checks each case of the switchstatement. The value 2doesn t match the topmost case, so the computer proceeds on to the middle of the three cases. The value posted for the middle case (the number 2) matches the value of the versevariable, so the computer executes the statements that come immediately after case 2. These two statements are out.println( That s because he is a pain. ); break; The first of the two statements displays the line That s because he is a pain.on the screen. The second statement is called a break statement. (What a surprise!) When the computer encounters a breakstatement, the computer jumps out of whatever switchstatement it s in. So, in Listing 5-6, the computer skips right past the case that would display Cause this is the last refrain.In fact, the computer jumps out of the entire switch statement and goes straight to the statement just after the end of the switch statement. The computer displays Ohhhhhhhh. . . .because that s what the statement after the switchstatement tells the computer to do. Figure 5-8: Running the code of Listing 5-6. If the pesky user asks for verse 6, the computer responds by dropping past cases 1, 2, and 3. Instead, the computer does the default. In the default, the computer displays No such verse. Please try again, and then breaks out of the switchstatement. After the computer is out of the switchstatement, the computer displays Ohhhhhhhh. . . . You don t really need to put a breakat the very end of a switchstatement. In Listing 5-6, the last break(the breakthat s part of the default) is just for the sake of overall tidiness.
We provides quality the CPanel Web Hosting. All our web hosting plans regular, business and expert are competitively priced and unsurpassed in reliability, uptime, and quality of service.