java面向对象计算鸡兔同笼完整代码
时间: 2024-01-13 21:02:42 浏览: 79
好的,以下是一份用Java面向对象思想来计算鸡兔同笼问题的完整代码:
Animal.java:
```java
public class Animal {
private String name;
private int count;
public Animal(String name, int count) {
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public int getCount() {
return count;
}
}
```
Chicken.java:
```java
public class Chicken extends Animal {
private int legs;
public Chicken(int count, int legs) {
super("鸡", count);
this.legs = legs;
}
public int getLegs() {
return legs;
}
}
```
Rabbit.java:
```java
public class Rabbit extends Animal {
private int ears;
public Rabbit(int count, int ears) {
super("兔", count);
this.ears = ears;
}
public int getEars() {
return ears;
}
}
```
Cage.java:
```java
public class Cage {
private Chicken chicken;
private Rabbit rabbit;
public Cage(Chicken chicken, Rabbit rabbit) {
this.chicken = chicken;
this.rabbit = rabbit;
}
public int calculate() {
int total = chicken.getCount() + rabbit.getCount();
int legs = chicken.getCount() * chicken.getLegs() + rabbit.getCount() * 4;
int ears = rabbit.getCount() * rabbit.getEars();
int chickenCount = (legs - ears) / 2;
int rabbitCount = total - chickenCount;
return rabbitCount;
}
}
```
Main.java:
```java
public class Main {
public static void main(String[] args) {
Chicken chicken = new Chicken(10, 2);
Rabbit rabbit = new Rabbit(28, 2);
Cage cage = new Cage(chicken, rabbit);
int rabbitCount = cage.calculate();
System.out.println("兔子的数量为:" + rabbitCount);
}
}
```
以上就是一份完整的Java面向对象计算鸡兔同笼问题的代码。希望能对你有所帮助。
阅读全文