母牛生母牛 用面向对象的思想实现这个算法

[b]问题描述[/b]
==================
农场一头小母牛,每年生头小母牛,母牛五岁产母牛,二十年后有多少牛?

[b]代码实现[/b]
==================

package com.cow.entity;
/**
* 母牛类
* @author Tanliwei
*/
public class Cow {
private int age;
private boolean firtility;
public Cow() {
}
public Cow(int age, boolean firtility) {
this.age = age;
this.firtility = firtility;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
// 大于五岁的牛可以进行生育
if (!firtility && age >= 5) {
this.setFirtility(true);
}
}
public boolean isFirtility() {
return firtility;
}
public void setFirtility(boolean firtility) {
this.firtility = firtility;
}
}


package com.cow;
import java.util.ArrayList;
import java.util.List;
import com.cow.entity.Cow;
/**
* 生产类
* @author Tanliwei
*/
public class Producer {
private int years = 20; // 生产年限
private int amount; //牛的数量
/**
* 母牛进行繁殖
*/
public List produce(){
List<Cow> cows = new ArrayList<Cow>();
//初始化 农场有一头可以生育的母牛
cows.add(new Cow(5,true));
amount += 1;
for(int i = 0; i < years; ++i){
pastAYear(cows);
}
return cows;
}
/**
* 一年以后的母牛群
* @param cows
* @return
*/
public List<Cow> pastAYear(List<Cow> cows){
Cow calf; //新生小牛
Cow term; //一群母牛中的一只
int currentAmount = cows.size(); //当前母牛的数量
for(int i = 0; i < currentAmount; ++i){ //母牛成长、生育,不包括新生的小牛
term = cows.get(i);
//这头母牛可以生育
if(term.isFirtility()){
calf = new Cow(1,false);
cows.add(calf);
amount += 1;
}
//母牛的年龄加一
term.setAge(term.getAge()+1);
}
return cows;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
}


package com.cow;
import java.util.List;
import com.cow.entity.Cow;
/**
* @author Tanliwei
*/
public class TestClass {
public static void main(String[] args) {
Producer producer = new Producer();
List<Cow> cows = producer.produce();
System.out.println("母牛总数:" + producer.getAmount());
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值