2021-04-03 选择结构训练任务 3
要求输入月份,判断该月所处的季节并输出季节(假设:12、1、2 月为冬季,依次类推)
使用switch语句case的穿透效果,当月份为12,1,2时,打印输出为冬季。当月份为3,4,5时,打印输出为春季。当月份为6,7,8时,打印输出为夏季。当月份为9,10,11时,打印输出为秋季。
代码如下:
import java.util.Scanner;
public class Class4_3 {
public static void main(String[] args) {
int inputMonth ;
Scanner input = new Scanner(System.in);//获取输入
System.out.println("请输入月份(1~12):");
//判断输入数据
if(input.hasNextInt()) {
inputMonth = input.nextInt();//赋值
//判断月份范围
if(inputMonth>0&&inputMonth<13) {
switch(inputMonth) {
case 12:case 1:case 2:
System.out.println(inputMonth+"月是冬季");break;
case 3:case 4:case 5:
System.out.println(inputMonth+"月是春季");break;
case 6:case 7:case 8:
System.out.println(inputMonth+"月是夏季");break;
case 9:case 10:case 11:
System.out.println(inputMonth+"月是秋季");break;
}
}else {
System.out.println("你输入的月份超出范围 "+inputMonth);
}
}else {
System.out.println("你输入的数据有误");
}
}
}
运行结果