Baby You Can Turn Me On |
Hi! This lesson is on something called a
switchstatement. You use it when you have a lot of choices (like a menu) and you want to do something different for each one. Although there are other ways to do this, they are less efficient (make your program slower) and make it easier to make mistakes.So let's use the menu as an example. Suppose we are writing part of a program which allows us to see people's details (name, age, etc.).
class Hello { public static void main(String[] args) { System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); } }So now we have a simple menu printed out. The next part of the program just reads a value as an
intfrom the keyboard. Don't worry about how it works. The only thing you need to know is that the value will be stored in the variablechoice. Don't forget theimportat the top (this will be explained in another lesson).
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); } }I'll write this program without using the
switchstatement at all to start with.
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); if (choice == 1) { System.out.println("Ben Golding"); } else if (choice == 2) { System.out.println("20 years"); } else if (choice == 3) { } else { System.out.println("Invalid choice " + choice); } } }Right, that's enough of that - let's try it out:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 1 Ben Golding [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 2 20 years [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 3 [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 7 Invalid choice 7 [nurmes]btg:You will have to keep running the program again and again, as it exits whichever option you choose.
Now we're going to add a
whileloop (remember those?) to keep the program running until we choose option 3. Notice thebreakstatement (I've highlighted it in blue) when we choose the exit option. Go back and check the loops lesson if you don't remember howbreakworks.
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); if (choice == 1) { System.out.println("Ben Golding"); } else if (choice == 2) { System.out.println("20 years"); } else if (choice == 3) { break; } else { System.out.println("Invalid choice " + choice); } System.out.println("-----------------"); } } }You should indent all the code that was there before. Try it out, and try entering various values (not just 1, 2 and 3) until you're clear on how the program works.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 1 Ben Golding ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 2 20 years ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 7 Invalid choice 7 ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 3 [nurmes]btg:I've also added a line to print out a separator (a line of dashes) each time we go around the loop again. Notice it isn't printed after we choose option 3 because of where the
breakstatement is.Right, now we're going to try to rewrite this exact same program without using
iforelse. To do that, we need toswitch.
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); switch (choice) { } System.out.println("-----------------"); } } }Don't try to compile it yet! I've thrown away all the iffy stuff, but we need to explain about
switcha bit before we have a complete program.So then - the first thing we have with a
switchstatement is a block like that one above. In the round brackets we put an expression which gives us an integer (byte,short,intorlong). Usually this is just the name of a variable, like in our example. We are also allowed to usechars, because they are really just the same asshorts (16 bit whole numbers).
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); switch (choice) { case 1: System.out.println("Ben Golding"); case 2: System.out.println("20 years"); } System.out.println("-----------------"); } } }Now it's partly finished. I expect you can guess how this works. We look at the value of
choiceand jump to the piece of code under the appropriatecase. Before we add any more to this, let's try it out.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 1 Ben Golding 20 years ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 2 20 years ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 1 Ben Golding 20 years ...When you get bored of doing that, hold down the Ctrl key and press C to kill the program (we haven't done exit yet). It looks like there's a problem, doesn't it? The problem is that the
switchjumps to the appropriatecaseand then continues on to the end of theswitch's block. So whenchoiceis1, it continues on to the code undercase 2too.The way to avoid this is to write
break, which causes the program to jump to the end of theswitch. Although it is optional, in most cases we writebreakjust before the nextcase.
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); switch (choice) { case 1: System.out.println("Ben Golding"); break; case 2: System.out.println("20 years"); break; } System.out.println("-----------------"); } } }The second
breakdoesn't actually make any difference, because it is at the very end of the block belonging to theswitchstatement. I put it there just to be safe.Now it should work:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 1 Ben Golding ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 2 20 years ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 1 Ben Golding ...Unfortunately now we have a problem with making the program exit, because we used
breakfor that before. In this case we can usereturninstead, which finishes themainmethod.If we have a
whileinside awhile, or aswitchinside awhilefor example, thebreakonly applies to the inner one. We can get around this problem by saying where tobreakto, as I will show you later in this lesson.Anyway, let's fix the exit option.
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); switch (choice) { case 1: System.out.println("Ben Golding"); break; case 2: System.out.println("20 years"); break; case 3: return; } System.out.println("-----------------"); } } }So let's assume that works (you can try it in a minute). What about if we enter an invalid value like 7? Previously we used the last
elseto deal with it. Inswitchwe writedefault(instead of anothercase). If none of thecases match the value, we go to thedefault. It's very easy so I'll just show you:
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (1-3):"); System.out.println("1 Print name"); System.out.println("2 Print age"); System.out.println("3 Exit"); int choice = Integer.parseInt(in.readLine()); switch (choice) { case 1: System.out.println("Ben Golding"); break; case 2: System.out.println("20 years"); break; case 3: return; default: System.out.println("Invalid choice " + choice); break; } System.out.println("-----------------"); } } }Again, I've put the last
breakin when it's not necessary. But see that thebreakaftercase 2is needed now. We could easily have forgotten to add it, if we hadn't earlier.Now we think everything works, we'd better try it:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Please select an option (1-3): 1 Print name 2 Print age 3 Exit 1 Ben Golding ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 2 20 years ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 7 Invalid choice 7 ----------------- Please select an option (1-3): 1 Print name 2 Print age 3 Exit 3 [nurmes]btg:Fantastic! Now remember earlier in this lesson I said that we can switch on any type of integer (
byte,intetc) or achar. Let's use A, B ,C instead of 1, 2, 3 for our menu. This means changing lots of things, including changing thecasestatements to have characters (between single quotes).
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (A-C):"); System.out.println("A Print name"); System.out.println("B Print age"); System.out.println("C Exit"); char choice = in.readLine().charAt(0); switch (choice) { case 'A': System.out.println("Ben Golding"); break; case 'B': System.out.println("20 years"); break; case 'C': return; default: System.out.println("Invalid choice " + choice); break; } System.out.println("-----------------"); } } }Make sure you use single and not double quotes for the characters. Notice that although a lot of the details have changed, the basic structure of the
switchis the same. Let's try the program out again.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Please select an option (A-C): A Print name B Print age C Exit A Ben Golding ----------------- Please select an option (A-C): A Print name B Print age C Exit B 20 years ----------------- Please select an option (A-C): A Print name B Print age C Exit a Invalid choice a ----------------- Please select an option (A-C): A Print name B Print age C Exit C [nurmes]btg:Good, so it does what we expected. But see when I try a small letter like
a, it doesn't work. Let's add a feature so that small letters are allowed too.
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please select an option (A-C):"); System.out.println("A Print name"); System.out.println("B Print age"); System.out.println("C Exit"); char choice = in.readLine().charAt(0); switch (choice) { case 'A': case 'a': System.out.println("Ben Golding"); break; case 'B': case 'b': System.out.println("20 years"); break; case 'C': case 'c': return; default: System.out.println("Invalid choice " + choice); break; } System.out.println("-----------------"); } } }Now we can use upper or lower case letters with exactly the same effect.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Please select an option (A-C): A Print name B Print age C Exit A Ben Golding ----------------- Please select an option (A-C): A Print name B Print age C Exit b 20 years ----------------- Please select an option (A-C): A Print name B Print age C Exit c [nurmes]btg:Now I want to show you one more trick - you won't have to use this very often, but when you do, it's really handy. Remember that I talked about using
breakto exit from the program? If we just writebreak, the compiler thinks that we just want to leave theswitchstatement, so the program doesn't exit (try it). We have to say that we also want to break out of thewhileloop. The way to do this is to label thewhileloop, and then give the name of the label when webreak.
import java.io.*; class Hello { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); mainLoop: while (true) { System.out.println("Please select an option (A-C):"); System.out.println("A Print name"); System.out.println("B Print age"); System.out.println("C Exit"); char choice = in.readLine().charAt(0); switch (choice) { case 'A': case 'a': System.out.println("Ben Golding"); break; case 'B': case 'b': System.out.println("20 years"); break; case 'C': case 'c': break mainLoop; default: System.out.println("Invalid choice " + choice); break; } System.out.println("-----------------"); } } }The label is the line just before the
while. It can be called whatever you like (using the same rules as names of variables), so long as thebreakuses the same name. Now try the program and you will find that it exits correctly.Play about with this as much as you like - try adding your own options to the menu and testing them. I'm finished with you for now, so please fill out the questionnaire before you go.
This is the End
Too patronising? Too complex? Typing error? Offended by traffic cones?
Got a question or something I should add? Send an email to ben_golding@yahoo.co.uk !
visits to this site
The contents of this site are copyright of Ben Golding