关于switch语句的使用方法---正在苦学java代码的新手之菜鸟日记 输入月份与年份,判断所输入的月份有多少天。

关于switch语句的使用方法---正在苦学java代码的新手之菜鸟日记
输入月份与年份,判断所输入的月份有多少天。

switch支持和不支持的类型

支持的类型

  1. int 类型
  2. short 类型
  3. byte 类型
  4. char 类型
  5. enum (枚举)类型 (java5.0 之后支持)
  6. String (java7.0之后支持)

不支持的类型

  1. long 类型
  2. boolean 类型
  3. float 类型
  4. double 类型
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		System.out.println("请输入年份:  ");
		int year=sc.nextInt();
		System.out.println("请输入月份:  ");
		int month=sc.nextInt();
		sc.close();
		if(month<=0||month>12) {
			System.out.println("你输入的月份有误,请重新输入...");
		}
		else {
		int days=switch(month) {
		case 1,3,5,7,8,10,12->31;
		case 4,6,9,11->30;
		default ->
		       year%4==0&&year%100==0||year%400!=0 ?29:28;
		};
	   System.out.printf("%d年%d月有%d天",year,month,days);	
		}
	}
	}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

结果如下

关于switch语句的使用方法---正在苦学java代码的新手之菜鸟日记
输入月份与年份,判断所输入的月份有多少天。

备注:
java 13 之后的 switch 语句支持表达式形式。

原文章:https://blog.csdn.net/Daihao__X/article/details/112061988