Java_基础语法之switch语句
1 /*switch 语句 2 格式: 3 switch(表达式) 4 { 5 case 取值1: 6 执行语句; 7 break; 8 case 取值2: 9 执行语句; 10 break; 11 ..... 12 default: 13 执行语句; 14 break; 15 } 16 17 */ 18 class SwitchDemo 19 { 20 public static void main(String[] args) 21 { 22 int x = 3; 23 switch(x)/*特点:1被选择的类型只能支持四种类型:byte short int char 24 2,备选答案并没有指定顺序,但是执行肯定时从第一个case开始,将每一个case都执行完,如果其中有匹配的case,执行完 25 通过case的break就结束了switch,如果没有一个case匹配,执行default。 26 27 switch语句结束只有两种情况:1 执行到了break 2 执行到了switch语句结束 28 */ 29 30 { 31 case 4: 32 System.out.println("a"); 33 break; 34 case 2: 35 System.out.println("b"); 36 break; 37 case 3: 38 System.out.println("c"); 39 break; 40 default: 41 System.out.println("d"); 42 break; 43 44 } 45 46 int a=4,b=2; 47 char ch ='+'; 48 switch(ch) 49 { 50 case'+': 51 System.out.println(a+b); 52 break; 53 case'-': 54 System.out.println(a-b); 55 break; 56 case'*': 57 System.out.println(a*b); 58 break; 59 case'/': 60 System.out.println(a/b); 61 break; 62 default: 63 System.out.println("nono") 64 65 66 } 67 68 System.out.println("Hello world!"); 69 70 } 71 72 73 }
switch语句练习
class SwitchTest { public static void main(String[] args) { /*int week =2; switch(week) { case 1: System.out.println(week+"是星期一"); break; case 2: System.out.println(week+"是星期二"); break; default: System.out.println(week+"不存在"); } System.out.println("Hello world!"); */ int month =4; /*switch(month) { case 3: System.out.println(month +"月是春季"); break; case 4: System.out.println(month +"月是春季"); break; case 5: System.out.println(month +"月是春季"); break; default: System.out.println(month +"月不存在"); break; }*/ switch(month) { case 3: case 4: case 5: System.out.println(month +"月是春季"); break; case 6: case 7: case 8: System.out.println(month +"月是夏季"); break; case 9: case 10: case 11: System.out.println(month +"月是秋季"); break; case 12: case 1: case 2: System.out.println(month +"月是冬季"); break; default: System.out.println(month +"月不存在"); break; } } }