public class MainClass {
public static void main(String[] args) {
int i = 1;
switch (i) {
case 1 :
System.out.println("One.");
break;
case 2 :
System.out.println("Two.");
break;
case 3 :
System.out.println("Three.");
break;
default:
System.out.println("You did not enter a valid value.");
}
}
}
The switch Statement: a demo
public class MainClass {
public static void main(String[] args) {
int choice = 2;
switch (choice) {
case 1:
System.out.println("Choice 1 selected");
break;
case 2:
System.out.println("Choice 2 selected");
break;
case 3:
System.out.println("Choice 3 selected");
break;
default:
System.out.println("Default");
break;
}
}
}
compile
Choice 2 selected
Execute the same statements for several different case labels |
|
public class MainClass {
public static void main(String[] args) {
char yesNo = 'N';
switch(yesNo) {
case 'n': case 'N':
System.out.println("No selected");
break;
case 'y': case 'Y':
System.out.println("Yes selected");
break;
}
}
}
compile
|
|
No selected |
Free Flowing Switch Statement Example |
|
public class Main {
public static void main(String[] args) {
int i = 0;
switch (i) {
case 0:
System.out.println("i is 0");
case 1:
System.out.println("i is 1");
case 2:
System.out.println("i is 2");
default:
System.out.println("Free flowing switch example!");
}
}
}
/*
i is 0
i is 1
i is 2
Free flowing switch example!
*/
|
|
Nested Switch Statements Example |
|
public class Main {
public static void main(String[] args) {
int i = 0;
switch (i) {
case 0:
int j = 1;
switch (j) {
case 0:
System.out.println("i is 0, j is 0");
break;
case 1:
System.out.println("i is 0, j is 1");
break;
default:
System.out.println("nested default case!!");
}
break;
default:
System.out.println("No matching case found!!");
}
}
}
//i is 0, j is 1
Switch statement with enum |
|
public class MainClass {
enum Choice { Choice1, Choice2, Choice3 }
public static void main(String[] args) {
Choice ch = Choice.Choice1;
switch(ch) {
case Choice1:
System.out.println("Choice1 selected");
break;
case Choice2:
System.out.println("Choice2 selected");
break;
case Choice3:
System.out.println("Choice3 selected");
break;
}
}
}
|
|
Choice1 selected |
|
|
http://www.java2s.com/Tutorial/Java/0080 __Statement-Control/Catalog0080__Statement-Control.htm |
No comments:
Post a Comment