Java & J2EE Page 4 - Conditionals, Expressions and Other Java Operators |
Sometimes you feel like some nuts. Sometimes you don't. Sometimes you also don't feel like writing a bunch of If-Elses all over the place. Well slacker, meet my little friend the Switch Statement. Public static void main(String args[]) { for(int launch_time = 0; launch_time < 11; launch_time++) switch(launch_time) { case 0: case 1: case 2: case 3: case 4: System.out.println("Shuttle launch in less than five seconds"); break; case 5: case 6: case 7: case 8: case 9: System.out.println("Shuttle launch in less than ten seconds"); break; default: System.out.println("Shuttle launch in less than 20 seconds");
} } } The above code (while it technically counts down backwards) will print the following to the screen: Shuttle launch in less than five seconds Shuttle launch in less than five seconds Shuttle launch in less than five seconds Shuttle launch in less than five seconds Shuttle launch in less than five seconds Shuttle launch in less than ten seconds Shuttle launch in less than ten seconds Shuttle launch in less than ten seconds Shuttle launch in less than ten seconds Shuttle launch in less than ten seconds Shuttle launch in less than 20 seconds Shuttle launch in less than 20 seconds If you had used the If-else statements you would have had to compare the value of launch_time each time to print out the result (ie; is launch_time greater than 1? is launch_time greater than 2, etc). It is possible to nest Switch statements as well, but that is beyond the scope of this tutorial. In fact, anything more is beyond the scope of this tutorial, as we have come to the end of it. Thanks for sticking around. In the next tutorial, I will go over the remaining statements (the Iteration and the Jump). So, hope to see you then. Till next time...
blog comments powered by Disqus |
|
|
|
|
|
|
|