Switch Code Segments
Introduction.
We have one last major decision related control structure to examine.
Think of situations where you have many different options such as a fairly
large variety of command buttons on a form. Many situations don't
require developing a mathematical expression for each possibility as we
saw with the If (expression) Else If (expression). These sorts
of situations where there are a fairly large variety of readily
identifiable conditions for altering program flow can often best be
implemented using switch code
segments. The basic syntax for the switch control structure follows.
Some Verbal Examples. We will start with some relatively common language examples and then progress to computer code.
While there is some obvious imprecision in our approach to determining whether someone is a freshman, sophomore, junior or senior you should get the idea. The switch variable must be either a byte, short, int or char. Notice the first three are numbers with no decimal places. We will present two examples, one that is based on an integer input, the other is based on character input. A Switch Based on a Number. In order to do something really scientific we are going to tell you everything you need to know about yourself based on your age. Unfortunately, this will probably be higher quality science than far too many things that try to masquerade under this impressive and overused term. You should call the applet AgePredictions.java. |
import javax.swing.JOptionPane; import javax.swing.JApplet; public class AgePredictions extends JApplet {
} // end class AgePredictions |
import javax.swing.*; import java.awt.Graphics; public class SwitchTest extends JApplet {
} // end SwitchTest |
Since the size of the applet window is important here is the SwitchTest.html. |
<html> <applet code="SwitchTest.class" width=300 height=250> </applet> </html> |
Make sure you try entering a number of different values
by using the restart option in the drop down box on the applet window. This code can be viewed as having three major sections. We don't have the usual error trapping since we have the default in the switch statement and everything can be brought in as a string.
The following image represents a user having selected c for the oval. |