Java程序流程控制之switch
java基础之流程控制(二)
二、分支控制语句 switch Statement
Java中有一个和if语句比较相似的分支控制语句叫switch ,它在有一系列固定值做分支时使用效率要比if-else方式效率高(别急,等一下再告诉你为什么效率高)。
先看一个例子:假设我们不考虑闰年的话,我们如何知道一个月有多少天?先用if-else的方式来实现:
java代码:
- public class demo2 {
- public static void main(String[] args) {
- int month=9;
- if(month==1){
- System.out.println(month+"月有31天");
- }else if(month==2){
- System.out.println(month+"月有28天");
- }else if(month==3){
- System.out.println(month+"月有31天");
- }else if(month==4){
- System.out.println(month+"月有30天");
- }else if(month==5){
- System.out.println(month+"月有31天");
- }else if(month==6){
- System.out.println(month+"月有30天");
- }else if(month==7){
- System.out.println(month+"月有31天");
- }else if(month==8){
- System.out.println(month+"月有31天");
- }else if(month==9){
- System.out.println(month+"月有30天");
- }else if(month==10){
- System.out.println(month+"月有31天");
- }else if(month==11){
- System.out.println(month+"月有30天");
- }else if(month==12){
- System.out.println(month+"月有31天");
- }else{
- System.out.println("没有这个月份吧");
- }
- }
- }
接下来我们使用switch语句重新实现一次:
java代码:
- public class demo2 {
- public static void main(String[] args) {
- int month = 9;
- switch (month) {
- case 1:
- System.out.println(month + "月有31天");
- break;
- case 2:
- System.out.println(month + "月有28天");
- break;
- case 3:
- System.out.println(month + "月有31天");
- break;
- case 4:
- System.out.println(month + "月有30天");
- break;
- case 5:
- System.out.println(month + "月有31天");
- break;
- case 6:
- System.out.println(month + "月有30天");
- break;
- case 7:
- System.out.println(month + "月有31天");
- break;
- case 8:
- System.out.println(month + "月有31天");
- break;
- case 9:
- System.out.println(month + "月有30天");
- break;
- case 10:
- System.out.println(month + "月有31天");
- break;
- case 11:
- System.out.println(month + "月有30天");
- break;
- case 12:
- System.out.println(month + "月有31天");
- break;
- default:
- System.out.println("没有这个月份吧");
- break;
- }
- }
- }
1、留意switch格式的写法
标准且合法的格式:

想要获得成功,首先要自己相信自己,再者要赢得周围朋友的信任!
浙公网安备 33010602011771号