Conditionals, Expressions and Other Java Operators - The Switch Statement (Page 4 of 4 )
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...
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |