1. 程式人生 > 其它 >關於switch語句的使用方法---正在苦練java程式碼的菜鳥日記

關於switch語句的使用方法---正在苦練java程式碼的菜鳥日記

技術標籤: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); } } }

結果如下

在這裡插入圖片描述

備註:
java 13 之後的 switch 語句支援表示式形式。