以判断今天是一年中的第几天为例
//输入月日,得到天数,先不考虑闰年的情况
Scanner sc = new Scanner(System.in);
System.out.println("month:");
int month = sc.nextInt();
System.out.println("day:");
int day = sc.nextInt();
int num = 0;
switch (month){
case 12: num += 30;
case 11: num += 31;
case 10: num += 30;
case 9: num += 31;
case 8: num += 31;
case 7: num += 30;
case 6: num += 31;
case 5: num += 30;
case 4: num += 31;
case 3: num += 28;
case 2: num += 31;
case 1: num += day;
default:break;
}
System.out.println(num+"day of year");
如果case语句后面不跟break,则会继续向下执行下一条case语句。