Switch Code Segments
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
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.
public class AgePredictions extends JApplet
} // end class AgePredictions
|You should be able to create your own
AgePredictions.html without my help.
The code can be seen as having three major sections
Notice how the indentation gets pretty deep. But this can be important when debugging.
A Switch Based on a Character. Now for something completely different, we will work with an applet that draws something in the applet window. The user's inputs are used to determine whether a line, rectangle or oval should appear. You should call the applet SwitchTest.java.
public class SwitchTest extends JApplet
} // end SwitchTest
|Since the size of the applet window is important here is the SwitchTest.html.|
<applet code="SwitchTest.class" width=300 height=250>
|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.