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+"月是冬季");

     }


}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值