switch case语句
格式:
switch(expression(表达式的值可以是byte,short,int,char)){
case value : //语句
break; //可选
case value : //语句
break; //可选
//你可以有任意数量的case语句
default : //可选
//语句 }
注:break:中断switch语句的执行。
default:所有的情况都不匹配时,就执行该处的的语句块.
实例一
输入年份和月份,输出相应的天数。
思路:
1.Scanner用法:导包,创建对象,接收数据。
2.使用变量:year,month,day
3.涉及到平闰年的判断(只有2月份需要单独考虑),使用switch进行。
package cn.tedu.day01;
import java.util.Scanner;
public class Year {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int year = sc.nextInt();
System.out.println("请输入月份");
int month = sc.nextInt();
int days = 31;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
days = ((year % 4 == 0 && year % 100 != 0 || year % 400 == 0)?29:28);
System.out.println(year + "年" + month + "月,有" + days );
sc.close();
}
}
}