Martrinex Learning Center
HOME CONTENTS
 
This website is underconstruction.
Author: Martin Sykes
Challenge: I have challenged myself to 1 article per day, and framework improvements! Enjoy
Challenge end: unknown

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;
}

Add Comment

Help the web master by commenting on the tutorials, thankyou.
Name:
Email: (this will not be shown)
Comment:
  Send email to admin, don't post.

 

Comments

Nobody has commented on this article.
Be the first, the webmaster needs comments good or bad to improve this site.



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.
Martrinex Learning Center[X]
  Introduction Beginner Intermediate

Important useful well commented source codes
Please read the import tutorial to know how to use them.

Source