语法
switch(){
case :
…
break;
…
default:
break;
}
switch语句使用注意事项
- 多个case后面的数值不可以重复
- switch后面的小括号当中只能是下列数据类型:
基本数据类型:byte/short/char/int
引用数据类型:String,enum枚举 - switch语句格式可以很灵活:前后顺序可以颠倒,而且break语句还可以省略;匹配哪一个case就从哪一个位置向下执行,知道遇到了break或者整体结束为止;
import java.util.Scanner;
public class Month {public static void main(String[] args) {Scanner read=new Scanner(System.in);System.out.println("输入月份:");int month= read.nextInt();switch(month){case 1: case 3: case 5: case 7: case 8: case 10: case 12:System.out.println("这个月是大月");break;case 4: case 6: case 9: case 11:System.out.println("这个月是小月");break;case 2:System.out.println("这个月是2月");break;default:System.out.println("输入的月份有错误");}}
}
格式解释说明:switch:说明这是switch语句。表达式:可以是byte,short,int,charJDK5以后可以是枚举JDK7以后可以是字符串case:后面的值就是要和表达式进行比较的值break:表示程序到这里中断,跳出switch语句default:如果所有的情况都不匹配,就执行这里,相当于if语句中的else