Chapter 5: Controlling Program Flow with Decision-Making Statements (Web hosting script)
Chapter 5: Controlling Program Flow with Decision-Making Statements 121 To break or not to break In every Java programmer s life, a time comes when he or she forgets to use breakstatements. At first, the resulting output is confusing, but then the programmer remembers fall-through. The term fall-through describes what happens when you end a case without a breakstatement. What happens is that execution of the code falls right through to the next case in line. Execution keeps falling through until you eventually reach a breakstatement or the end of the entire switchstatement. Usually, when you re using a switchstatement, you don t want fall-through, so you pepper breakstatements throughout the switchstatements. But, occasionally, fall-through is just the thing you need. Take, for instance, the Al s All Wet song. (The classy lyrics are shown in the sidebar bearing the song s name.) Each verse of Al s All Wet adds new lines in addition to the lines from previous verses. This situation (accumulating lines from one verse to another) cries out for a switchstatement with fall-through. Listing 5-7 demonstrates the idea. Listing 5-7: A switch Statement with Fall-Through import static java.lang.System.out; import java.util.Scanner; class FallingForYou { public static void main(String args[]) { Scanner myScanner = new Scanner(System.in); out.print( Which verse? ); int verse = myScanner.nextInt(); switch (verse) { case 3: out.print( Last refrain, ); out.println( last refrain, ); case 2: out.print( He s a pain, ); out.println( he s a pain, ); case 1: out.print( Has no brain, ); out.println( has no brain, ); } out.println( In the rain, in the rain. ); out.println( Ohhhhhhhh… ); out.println(); } }
We will hook you up with a JSP web hosting at the great rate, check our jsp web hosting, and join us today!!!