Switch, case, and break
In this section, we're going to take a look at the switch statement, which is another way that we can modify the control flow of our program.
To begin, let's create a new project in NetBeans. At my end at least, I'm going to get rid of all these comments. To demonstrate the power of the switch statement, we're going to start by writing a program using only if blocks, then we'll convert the program to one that uses switch statements. The following are the steps for the program that uses only if blocks:
- To begin, let's simply declare a variable
x, (int x =1;), and here is our goal: If the value ofxis1,2, or3, we'd like to print out the responsesRED,BLUE, orGREEN, respectively. Ifxis not one of those numbers, we'll just print out a default response.
- Doing this with
ifblocks is pretty straightforward, if not a little tedious:
if(x == 1)
{
System.out.println("RED")
} Then, we'll pretty much just copy and paste this block of code and modify it for the blue and...