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

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

代码实现
==================
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 cows = new ArrayList();
		//初始化 农场有一头可以生育的母牛
		cows.add(new Cow(5,true));
		amount += 1;
		for(int i = 0; i < years; ++i){
			pastAYear(cows);
		}
		return cows;
	}	
	/**
	 * 一年以后的母牛群
	 * @param cows
	 * @return
	 */
	public List pastAYear(List 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 cows = producer.produce();			
		System.out.println("母牛总数:" + producer.getAmount());		
	}
}

转载于:https://www.cnblogs.com/tanliwei/archive/2011/04/02/9102673.html

你可能感兴趣的:(母牛生母牛 用面向对象的思想实现这个算法)