根据用指定的月份,打印该月所属的季节(if else)3,4,5 春季 6,7,8 为夏季 9,10,11 秋季 12,1,2为冬季(switch 与 if(){}else{})两种写法

it2026-09-03  5

package work.com.cn.entity; /* 根据用于指定月份,打印该月份所属的季节。 3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季 */ import java.util.Scanner; public class SwitchScannerTest { public static void main(String[] args) { //方法一 Scanner season = new Scanner(System.in); System.out.print("请输入月份(1-12):"); int y = season.nextInt(); switch (y){ case 3: case 4: case 5: System.out.println("春天(spring)"); break; case 6: case 7: case 8: System.out.println("夏天(summer)" ); break; case 9: case 10: case 11: System.out.println("秋天(autumn)"); break; case 12: case 1: case 2: System.out.println("冬天(winter)"); break; default: System.out.println("季节输入有误"); } //方法二 Scanner scanner = new Scanner(System.in); System.out.print("请输入月份(1-12):"); int x = scanner.nextInt(); if (x >= 3 && x <= 5) { System.out.println(x+"月是春季!"); } else if (x >= 6 && x <= 8) { System.out.println(x+"月是夏季!"); } else if (x >= 9 && x <= 11) { System.out.println(x+"月是秋季!"); } else if (x == 1 || x == 2||x == 12) { System.out.println(x+"月是冬季!"); } else { System.out.println("你的输入有误!"); } } }
最新回复(0)