Presentation is loading. Please wait.

Presentation is loading. Please wait.

The switch statement: an alternative to writing a lot of conditionals

Similar presentations


Presentation on theme: "The switch statement: an alternative to writing a lot of conditionals"— Presentation transcript:

1 The switch statement: an alternative to writing a lot of conditionals

2 Suppose we have a user input and we have a lot of conditions to consider. Currently, we would write a group of conditional statements to deal with this. We have another way of dealing with this situation. It is known as a “switch” command. This command takes in variable and determines what you want to do with the variable.

3 Example int num1 = key.nextInt(); I want to do different things based on the input of the variable. The switch command allows for this. switch(num1) { // code inside }

4 Inside the switch statement
switch(num1) { case 1: // some action case 2: // some action case 3: // some action } In the code above, you use the reserved word case to test conditions. If num1 = 1, the action in case 1 will executed.

5 Inside the switch statement
switch(num1) { case 1: // some action break; case 2: // some action case 3: // some action default: // some action } The break command will stop any further evaluation if a condition is hit. The default executes if none of the conditions are hit.

6 The following code is equivalent
int num1 = key.nextInt(); switch(num1) { case 1: // some action break; case 2: // some action case 3: // some action break default: // some action } int num1 = key.nextInt(); if(num1 == 1) // some action else if(num1 == 2) else if(num1 == 3) else

7 Case statement can handle any variables
String s1 = key.nextLine(); switch(s1) { case “a”: // some action break; case “c”: // some action case “d”: // some action default: // some action }


Download ppt "The switch statement: an alternative to writing a lot of conditionals"

Similar presentations


Ads by Google