我们定义3、4、5月为春天,6、7、8月为夏天,9、10、11月为秋天,12、1、2月为冬天。我最先想到的是用if语句:
public class test1 { public static void main(String[] args) { int mo=3; //要判断的月份 if (mo>=3 && mo<=5){ System.out.println(mo+"月份是春季"); }else if(mo>=6 && mo<=8){ System.out.println(mo+"月份是夏季"); }else if(mo>=9 && mo<=11){ System.out.println(mo+"月份是秋季"); }else{ System.out.println(mo+"月份是冬季"); } } }
同样可以利用switch的穿透性来判断季节:
public class test1 { public static void main(String[] args) { int i=3; //要判断的月份 switch (i){ case 3: case 4: case 5: //switch的穿透性 System.out.println("春天"); break; case 6: case 7: case 8: System.out.println("夏天"); break; case 9: case 10: case 11: System.out.println("秋天"); case 12: case 1: case 2: System.out.println("冬天"); default break; } } }
这里运用了switch的穿透性,即一个case中没有break结束的话会一直执行下去