//告知對方他輸入的是幾月、本月有幾天,注意二月有兩種答案28或29
package tw.xxx.xxx.copy.flowcontrol;
public class TestIfElseIfEx1 {
public static void main(String[] args) {
int month = 2;//選擇輸入二月
if(month==1|month==3|month==5|month==7|month==8|month==10|month==12){//"|"是or的意思
System.out.println("你所查詢的是"+month+"月,本月有31天。");
}else if(month==4|month==6|month==9|month==11){ //當if的條件不成立時,往else if跑,要是再不成立就再往下跑
System.out.println("你所查詢的是"+month+"月,本月有30天。");
}else if(month==2){
System.out.println("你所查詢的是2月,本月可能有28天或者29天,端看今年是否閏年。");
}else{
System.out.println("你所查詢的月份並不存在。");
}
}
}
你所查詢的是2月,本月可能有28天或者29天,端看今年是否閏年。
//告知對方他輸入的是幾月、本月有幾天,注意二月有兩種答案28或29
//使用case作答
package tw.xxx.xxx.copy.flowcontrol;
public class TestIfElseIfEx2 {
public static void main(String[] args) {
int month = 9;
switch(month){//放入待檢測變數
case 1://若變數為1,case只可檢視數值或字元
System.out.println("31天");
break;//注意,沒寫break的話他會從符合的那個開始繼續做下去!
//可以試試看輸入大月份跟小月分的差異,因為小月份故意沒放break,所以會顯示數字很多次
case 3:
System.out.println("31天");
break;
case 5:
System.out.println("31天");
break;
case 7:
System.out.println("31天");
break;
case 8:
System.out.println("31天");
break;
case 10:
System.out.println("31天");
break;
case 12:
System.out.println("31天");
break;
case 4:
System.out.println("1-30天");
case 6:
System.out.println("2-30天");
case 9:
System.out.println("3-30天");
case 11:
System.out.println("4-30天");
break;
case 2:
System.out.println("28或29天");
default://類似else
System.out.println("錯誤");
}
}
}
若輸入3:
31天
若輸入9:(因為沒有放break)
3-30天
4-30天
若輸入13:
錯誤
default也可以不要放在最後,他一樣會往下去找符合的最後才來用default
//同上面,簡化寫法
package tw.xxx.xxx.copy.flowcontrol;
public class TestIfElseIfEx3 {
public static void main(String[] args) {
int month = 4;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("31");
break;//break一出現,代表跳出switch了
case 2:
System.out.println("28或29");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println("30");
break;
default :
System.out.println("錯誤");
break;
}
}
}