This examples uses the a set of tax codes to decide the amount of taxt to be charged.
switch(tax_Code)
{
case "T1":
taxRate=0
break;
case "T2":
taxRate=20
break;
case "T3":
taxRate=40
default:
taxRate=20
}
This example assumes a two-player game where the winner is first to gain a laed of three points. It uses the relative values of two players’ scores to set a feedback message held in the variable scoreMessage.
var P1=Player1_SCORE
var P2=Player2_SCORE
switch(P1)
{
case P2+1:
scoreMessage="Player 1 is edging into the lead"
break;
case P2-1:
scoreMessage="Player 2 is edging into the lead"
break;
case P2+2:
scoreMessage="Match Point Player 1"
break;
case P2-2:
scoreMessage="Match Point Player 2"
break;
case P2+3:
scoreMessage="Winner - Player 1"
gameOver=true
break;
case P2-3:
scoreMessage="Winner - Player 2"
gameOver=true
break;
default
scoreMessage="Scores are Tied"
}
In this example the numbers of the months of the year are used to assign the number of days they contain to the variable numDays. The statement selects those with 31 days by number, has a special case for February but otherwise assigns 30 to numDays as all the rest have 30 days.
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 10:
case 12:
numDays=31
break;
case 2:
numDays=28
break;
default
numDays=30
break;
}
Let us suppose that you are checking a student’s answer for keywords and there are several ways of describing a process. You might want to award three marks for the correct scientific term, two for the more general description and one for a vague approximation.
As an example let’s evaluate three possible answers to the question. What makes water vapour move about randomly above a hot coffee? The example supposes we have stored the answer in a variable userResponse
switch(userResponse)
{
case "Brownian motion":
SCORE+=1
case "heat":
SCORE+=1
case "steam":
SCORE+=1
default:
NumQuestions++
break;
}
Here we automatically award 3 marks if the student thinks Brownian motion is involved because they get 1 for the "Brownian motion" case and one for the cases below this one. The answer "steam" would only score 1 mark.
Note that the default case is used to increase the count of the number of questions answered and applies in all three cases.
If we were being uncharitable and wished students to be penalised a mark if they did not get any of these answers then we would use:
switch(userResponse)
{
case "Brownian motion":
SCORE+=1
case "heat":
SCORE+=1
case "steam":
SCORE+=1
break;
default:
SCORE-=1
break;
}
Here the correct answers work in the same way utilising the fall through so the score is additive but we stop the fall through before the default by using break so that the default actions are only performed if none of the above cases apply.