1. 程式人生 > >if語句練習2

if語句練習2

                                                  if語句練習——季節

一年有四季

春季:3. 4 . 5

夏季:6. 7 . 8

秋季:9 . 10. 11

冬季:12 .1 .2

根據使用者輸入的月份,給出對應的季節。

思路:

使用者輸入無法獲取但是那只是具體資料的一種獲取手段而已,

而我們要做的功能僅僅是對使用者指定的資料進行對應星期的

列印而已。

所以具體的資料不確定,完成可以使用變數來表示。

我們只對變數進行操作即可,至於變數的值,可以有使用者來

決定。

因為資料的不確定性,所以要對資料進行判斷。

使用if語句。

例1:

class DemoIf

{    public static void main(String[] args){

        int mSonth;//——>客戶資料不確定,來個變數

        if(month==3)//——>這個是判斷

            {

                System.out.println(month+"月是春季");

            }

         else if(month==4){

                System.out.println(month+"月是春季");

            }   

    }

}

這樣寫很多都重複了。

注:開發者有個原則性問題,提高程式碼的複用性。所謂的複用性

,指的是程式碼的重複使用程度,。就是這個東西我一寫完就能用。

怎麼使用複用性?

複用的方法有很多種,現在只說一種。將條件合併。

注:將多個條件合併成一個,這個時候就可以用邏輯運算子來連線。

例2:

class DemoIf2

{    public static void main(String[] args){

         int  month=4;

         if(month==3||month==4||month==5){

                System.out.println(month+"月是春季");

        }

          else if(month==6||month==7month==8){

                 System.out.println(month+"月是夏季");

        }

           else if(month==9||month==10||month==11){

                   System.out.println(month+"月是秋季");

        }

            else if(month==12||month==1month==2){

                    Syetem.out.println(month+"月是冬季");

        }

             else

                      Syeem.out.println(month+"月沒有對應的季節");

    }

}

這樣寫還是比較麻煩。

既然是區間,我們可以這樣 寫if(month>=3&&month<==5)

注:這兩個是boolean型,需要連線。

例3:

class DemoIf3

{    public static void main(String[] args){

            int  month=13

            if(month<1||month>12){

                    System.out.println(month+"月沒有對應的季節");

           }

             else if(month>=3&&month<=5){

                     System.out.println(month+"月是春季");   

            }

               else if(month>=6&&month<=8) {

                       Syetem.out.println(month+"月是夏季"); 

            }

                else if(month>=9&&month<=11){

                        System.out.println(month+"月是秋季");

            }

                  else 

                        Syetem.out.println(month+"月是冬季");

}

}