
说明
1、在switch语句中,变量类型可以是:byte、short、int或char。自JavaSE7以来,switch支持字符串String类型,而case标签必须是字符串常量或字面量。
2、switch句子可以有多个case句子。每个case后面都有一个值和冒号。
3、switch句子可以包含一个default分支,通常是switch句子的最后一个分支(可以在任何位置,但通常在最后一个)。default执行时没有case句子的值和变量值相等。default分支不需要break句子。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | Scanner in = new Scanner(System. in );
System.out.println( "请输入当前月份" );
int month = in .nextInt();
switch (month){
case 1 :
System.out.println( "一月" ); break ;
case 2 :
System.out.println( "二月" ); break ;
case 3 :
System.out.println( "三月" ); break ;
case 4 :
System.out.println( "四月" ); break ;
case 5 :
System.out.println( "五月" ); break ;
case 6 :
System.out.println( "六月" ); break ;
case 7 :
System.out.println( "七月" ); break ;
case 8 :
System.out.println( "八月" ); break ;
case 9 :
System.out.println( "九月" ); break ;
case 10 :
System.out.println( "十月" ); break ;
case 11 :
System.out.println( "十一月" ); break ;
case 12 :
System.out.println( "十二月" ); break ;
default :
System.out.println( "错误的输入" ); break ;
}
|
以上就是java switch语句的介绍,希望对大家有所帮助。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。