Java Switch
You already know how to check for one thing at a time with the 'if' statement now I will show a faster way to check for and run code for multiple different outcomes.
Sample
Code:
switch(variable_to_check){
case 1:
/* code if its 1 here */
break;
case 2:
/* code if its 2 here */
break;
case 3:
/* code if its 3 here */
break;
case 4:
/* code if its 4 here */
break;
case 5:
/* code if its 5 here */
break;
default: /* same as else in if, so anything other thene 1,2,3,4,5 */
/* run else code here */
break;
}
Explanation
The switch statement, selects a variable to check
and then you can use 'case' to check that variable for a value,
place your code under the 'case', break tells it to end the code.
default is used at the bottom like 'else' is used in the if statement.
The or '||' statement
Ok so switch doesn't really have an 'or' statement if variable=1 or 2 run same code but their is a trick, simply don't provide any code, for example:
Code:
switch(variable){
case 1:
case 2:
/*place code here for 1 or 2 */
break;
case 3:
/*place code here for 3 */
break;
}
Copyright (c) 2008, Martin Sykes.
Learning Center is a branch of Martrinex Systems, Martrinex.net
Do not copy any materials from this site without permission from the auther.
Add Comment
Comments