Java & J2EE Page 3 - Java Statements |
Part of being a bratty kid is testing your limits. How many times can I get a cookie out of the cookie jar before my parents notice; how many times can I put the dog in a pillow case and swing it in the air before it bites me? As I said previously, if the value of the timer was not greater than 0, the program would have skipped the loop entirely. Sometimes however, we want the program to execute the loop at least once. For that, we use the Do-While. Class CountDown { public static void main(String args[]) { int timer = 10; do { System.out.println(“T minus “ + timer); timer--; } while(timer > 0); } } The sample above will once again result in the following: T minus 10 T minus 9 T minus 8 T minus 7 T minus 6 T minus 5 T minus 4 T minus 3 T minus 2 T minus 1 The difference however is that even if timer had not been greater than 0, it still would have printed the following: T minus 10 Let's make a program where you get to select your own punishment for being bad. class YourBeating { public static void main(String args[]) char punishment; do { System.out.println(“You've been very bad.”); System.out.println(“Please select your punishment:”); System.out.println(“1: A firm talking to.”); System.out.println(“2: A spanking.”); System.out.println(“3: Forced to watch the View all day.”); System.out.println(“4: Be pitied by the poet Mr. T.n”); favorite = (char) System.in.read(); } while( favorite < '1' || favorite > '4'); System.out.println(“n”); switch(favorite) { case '1': System.out.println(“Prepare to be bored! Let the talking commence!”); break; case '2': System.out.println(“I'll spank you so hard your He-Man underoos will turn into Strawberry Shortcake!”); break; case: '3': System.out.println(“Forced to watch the View...A worse punishment I could not imagine.”); break; case '4': System.out.println(“Mr. T has pitied your greatly!”); break; } } } The above code lists a bunch of possible punishments (four in total). If the user presses any key other than 1,2,3, or 4, the program will simply loop again, giving them their four options. If they chose say punishment four, the following would print out to the screen: Mr. T has pitied you greatly!
blog comments powered by Disqus |
|
|
|
|
|
|
|