【Java】巢狀if-else if 練習題 考古題 題目 考題 面試考題

練習題與實作

此篇主要為在【 資策會 】上課時的【 Java 】 課程 筆記,針對基本架構【巢狀if-else if 】的【 練習題 】【考古題】。

【巢狀if-else if 】相關解說請閱讀【 Java基本架構(3):巢狀if-else if 】,內有詳細說明。


練習題 一 (月份與天數)

目標:設定一個月份,判斷當月天數為多少。

       int month=4;
       if (month==1||month==3||month==5||month==7||month==8||month==10
          ||month==12) {
                 System.out.println(month+” has 31 days”);
        } else if (month==4||month==6||month==9||month==11){
                System.out.println(month+”month  has 30 days”);
        } else if (month==2) {
                System.out.println(month+”month  has 28-29 days”);
       } else {
               System.out.println(month+” month  is wrong”);
       }

結果:
4 month has 30 days


練習題 二 (正負數與奇偶數)

目標:設定一個數,判斷是正負數以及積偶數。

      int num1=22;
      if(num1>=0)                 //值>0
      {
              if (num1%2==0)   //值>0 且被2整除
              {
                       System.out.println(num1+”是正數,且為偶數”);
              }
              else                     //值>0 且不被2整除
              {
                       System.out.println(num1+”是正數,且為奇數”);
             }
     }
    else                               //值<0
    {
             if (num1%2==0)   //值<0 且被2整除
             {
                      System.out.println(num1+”是負數,且為偶數”);
              }
              else                    //值<0 且不被2整除
             {
                       System.out.println(num1+”是負數,且為奇數”);
              }
      }

結果:
22是正數,且為偶數


Related Posts

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js