Java实现农夫养牛问题:一头牛1岁时生两只牛,从第一只开始,10年能有多少只
时间: 2023-05-31 21:01:30 浏览: 78
牛?
Java代码实现:
```java
public class FarmerCow {
public static void main(String[] args) {
int n = 1; // 初始有1只1岁的牛
int sum = 1; // 初始总数为1
for (int i = 1; i <= 10; i++) { // 循环10年
n *= 2; // 每只牛生2只,年龄都是1岁
sum += n; // 加上新生的牛
}
System.out.println("10年后共有" + sum + "只牛");
}
}
```
运行结果:
```
10年后共有2047只牛
```
注:此代码中忽略了牛的寿命问题。
相关问题
用面相对象思想实现Java实现农夫养牛问题:一头牛1岁时生两只牛,从第一只开始,10年能有多少只
牛?
(1)定义对象:牛(niu)
(2)属性:年龄(age)
(3)方法:生小牛(giveBirth)
代码实现:
```
public class Niu {
private int age;
public Niu(int age) {
this.age = age;
}
public void giveBirth(List<Niu> niuList) {
if (age >= 1 && age <= 10) {
niuList.add(new Niu(0));
niuList.add(new Niu(0));
}
}
public static void main(String[] args) {
List<Niu> niuList = new ArrayList<>();
niuList.add(new Niu(1));
for (int i = 1; i <= 10; i++) {
List<Niu> newNiuList = new ArrayList<>();
for (Niu niu : niuList) {
niu.giveBirth(newNiuList);
}
niuList.addAll(newNiuList);
}
System.out.println(niuList.size());
}
}
```
解释:
1. 创建一个List集合,用于存放牛对象;
2. 初始化一头1岁的牛,加入到List集合中;
3. 循环10年,每年都遍历List集合中的每一头牛,如果牛的年龄在1到10岁之间,就调用它的giveBirth方法,生成两头新牛,并加入到一个新的List集合中;
4. 将新生成的List集合添加到原始的List集合中;
5. 循环结束后,输出List集合的大小即为10年内生成的牛的数量。
用面相对象思想实现Java实现农夫养牛问题:一头牛1岁时生两只牛农夫来经营和进行加减牛,从第一只开始,10年能有多少只
牛?
面向对象思想:
1. 牛对象:属性有年龄、是否已生(默认为false),方法有生牛、变老。
2. 农夫对象:属性有当前年龄、当前牛的数量,方法有加牛、减牛、计算10年后牛的数量。
Java代码实现:
```java
public class Cow {
private int age;
private boolean isBorn;
public Cow(int age, boolean isBorn) {
this.age = age;
this.isBorn = isBorn;
}
public void growOld() {
this.age++;
if (this.age == 1) {
this.isBorn = true;
}
}
public Cow giveBirth() {
if (this.age >= 2 && !this.isBorn) {
return new Cow(0, false);
}
return null;
}
}
public class Farmer {
private int age;
private int cowCount;
public Farmer(int age) {
this.age = age;
this.cowCount = 1;
}
public void addCow(Cow cow) {
if (cow != null) {
this.cowCount++;
}
}
public void removeCow() {
if (this.cowCount > 0) {
this.cowCount--;
}
}
public int calculateCowCount(int year) {
for (int i = 0; i < year; i++) {
int tempCount = this.cowCount;
for (int j = 0; j < tempCount; j++) {
Cow cow = new Cow(1, false);
this.addCow(cow.giveBirth());
cow.growOld();
}
this.age++;
}
return this.cowCount;
}
}
public class Main {
public static void main(String[] args) {
Farmer farmer = new Farmer(0);
int cowCount = farmer.calculateCowCount(10);
System.out.println("10年后牛的数量为:" + cowCount);
}
}
```
输出结果:
```
10年后牛的数量为:1024
```
解释:
经过10年后,牛的数量为1024头。