輸入月份與年份,判斷所輸入的月份有多少天,
switch支持和不支持的型別
支持的型別
- int 型別
- short 型別
- byte 型別
- char 型別
- enum (列舉)型別 (java5.0 之后支持)
- String (java7.0之后支持)
不支持的型別
- long 型別
- boolean 型別
- float 型別
- 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 陳述句支持運算式形式,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/243998.html
標籤:java
