關於switch語句的使用方法---正在苦練java程式碼的菜鳥日記
阿新 • • 發佈:2021-01-02
技術標籤:java
輸入月份與年份,判斷所輸入的月份有多少天。
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 語句支援表示式形式。