(1).switch的表达式只能是byte int short char String(jdk1.7以后)
package com.ccy.demo;
public class Dome5 {
public static void main(String[] args) {
/**
* switch的表达式只能是byte int short char String类型(jdk1.7以后)
* switch适合于等值判断
* 如果没有break没有知道遇见break才结束程序
*/
// 定义一个变量 grade
int grade = 4;
switch(grade){ // 定义的变量要和switch类型要一样
case 1:
System.out.println("*");
break; // 跳出switch
case 2:
System.out.println("**");
break; // 跳出switch
case 3:
System.out.println("***");
break; // 跳出switch
case 4:
System.out.println("****");
break; // 跳出switch
default: // 都不符合就到default 跳出switch
System.out.println("没有匹配上");
break; // 跳出switch
}
System.out.println("程序结束!!!");
}
}
(2).练习输入对应的月份得出对应的天数
package com.ccy.demo;
public class Dome6 {
public static void main(String[] args) {
/**
* 输入月份算出对应的天数
* 分析
* 31 : 1,3,5,7,8,10,12
* 30 : 4,6,9,11
* 28 : 平年
* 29 : 闰年
* 平年和闰年怎么判断(year % 400 == 0 && year % 4 == 0 || year%100 != 0 “说明是闰年” );
*/
// 定义两个变量 yaer month
int year = 2000;
int month = 2;
int day = -1;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
//下面我们来判断是否为: 闰年
case 2:
if((year % 400 ==0 )|| (year %4 == 0 && year %100 !=0)){
day = 29;
}else {
day = 28;
break;
}
default:
if ((day <= 0) && ( day > 12 ))
System.out.println("输入月份错误!!!");
}
System.out.println(year+"年"+month+"月共有:"+day+"天");
}
}