猫抓老鼠

您所在的位置:网站首页 猫和老鼠游戏取名叫什么名字 猫抓老鼠

猫抓老鼠

2024-06-30 15:00| 来源: 网络整理| 查看: 265

    我们先设计一个猫抓老鼠的小游戏:

    ⊙猫和老鼠都有名字和体重两种属性,猫有抓老鼠的方法,对应的老鼠则有逃跑的方法。

    ⊙首先游戏的结果是猫抓住了老鼠或者老鼠逃跑了,对于这两种情况,我们用体重来区分,若猫的体重大于或等于老鼠的体重,则猫可实现抓住老鼠的方法,若猫的体重小于老鼠的体重,则老鼠实现了逃跑的方法。

    分析一下,第一步我们需要建立两个类:Cat、Mouse;并且分别声明其各自拥有的方法:

 //Cat.java package Testprogramming //打包语句,将Cat类存于TestProgramming包中随后解释其作用; Public class Cat{     public String name;     public int weight;     Cat(){     //注意为了不至于在创建Cat类的实例化对象的时候出现错误,我们最好写一个空的构造方法     //若没有它则Cat cat=new Cat();语句会报错!至于猫的属性,可以用相应的get/set方法获得         }     Cat(String name,int weight){         this.name=name;         this.weight=weight;             }     //下面补上相应的get/set方法     public String getName(){         return name;         }     public void setName(String name){         this.name             }     public int getWeight(){         return weight;         }     publuc void setWeight(int weight){         this.weight;         }     //重写Object类的toString方法,以得到猫的信息     public String toString(){         return "Cat [名字=" + name + ", 体重=" + weight + "]";         }      //最后声明猫抓老鼠的方法,因为猫抓住的是老鼠这一类动物,所以返回值类型应该是个Mouse类     public Mouse catchMouse(Mouse mouse){         return mouse         } } //Mouse类的构成和Cat类基本相同 //Mouse.java package Testprogramming public class Mouse{     public String name;     public int weight;     Mouse(){              }     Mouse(String name,int weight){         this.name=name;         this.weight=weight;         }       public String getName(){         return name;         }     public void setName(String name){         this.name             }     public int getWeight(){         return weight;         }     publuc void setWeight(int weight){         this.weight;         }     public String toString(){         return "Mouse [名字=" + name + ", 体重=" + weight + "]"         }      public Cat escapeCat(Cat cat){             return cat;         }         //若猫的体重小于老鼠的体重,则老鼠可以实现逃跑的方法     public static void inform(boolean b){ if(b==false){ System.out.println("猫抓住了老鼠"); }else{ System.out.println("猫抓老鼠游戏中,老鼠体重超标,猫输了游戏"); }          }

    下面我们编写测试类,实例化一下Cat和Mouse类

    

//Test_Cat_Mouse.java package Testprogramming public class Test_Cat_Mouse{     public static void main(String[] args){     String string1,string2;     boolean boolean;     //首先实例化一个Cat、Mouse     Cat catTom=new Cat("Tom",50);     Mouse mouseLisa=new Mouse("Lisa",40);     if(!((bool=mouseLisa.getWeight()==catTom.getWeight())                 &&(bool=mouseLisa.getWeight()


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3