飞道的博客

基于面向对象实现:猫抓老鼠小游戏 有一只猫和一只老鼠,当猫的体重是小于老鼠体重的5倍时,猫可以抓到老鼠。

409人阅读  评论(0)

有一只猫和一只老鼠,当猫的体重是小于老鼠体重的5倍时,猫可以抓到老鼠,

猫每吃掉一只老鼠,体重增加老鼠的体重的0.5倍,

但是当猫的体重超过了老鼠体重的5倍,猫无法抓到老鼠,老鼠逃脱并对猫发出嘲讽。

创建一个Cat类
public class Cat {
   
 private String name;
 private double weight;
 
 Cat() {
    
 }
public Cat(String name, double weight) {
   
  super();
  this.name = name;
  this.weight = weight;
 }
 public String getName() {
   
  return name;
 }
public void setName(String name) {
   
  this.name = name;
 }
 public double getWeight() {
   
  return weight;
 }
public void setWeight(double weight) {
   
  this.weight = weight;
 }
 public void catchMouse(Mouse jerry) {
   
  System.out.println("抓到啦");
  
 }      
创建一个Mouse类
public class Mouse {
   
 private String name;
 private double weight;
 
 Mouse() {
   
  
 }
 public Mouse(String name, double weight) {
   
  super();
  this.name = name;
  this.weight = weight;
 }
 public String getName() {
   
  return name;
 }
 public void setName(String name) {
   
  this.name = name;
 }
 public double getWeight() {
   
  return weight;
 }
public void setWeight(double weight) {
   
  this.weight = weight;
 }
 public void haha() {
   
  System.out.println("jerry说 :hahaa,你这个笨蛋");
  
 }
 }
创建一个Test_Mouse_Cat类
public class Test_Mouse_Cat {
   
public static void main(String[] args) {
   
 Mouse jerry = new Mouse("jerry",2);
 Cat Tom = new Cat("Tom",6);
 int count =0;
 
 double j =Tom.getWeight();
 while (j/2<5) {
   
 Tom.catchMouse(jerry);
   j+=1;
   count++;
   System.out.println("抓到"+count+"次");
   }jerry.haha();
 }
 }

转载:https://blog.csdn.net/weixin_45985600/article/details/109551597
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场