牛生牛的问题

以前记得在学习java的时候留了一个牛生牛的问题没有解决,今晚突然想起了于是就简单的写了一下,问题大概如下:初生小牛到五岁才能再生小牛,现在农场有一头初生小牛,20年后一共会有多少头

package sina.CreAmazing.sf;

import java.util.ArrayList;

public class Test1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//为农场添加初始的小牛
		ArrayList<Cow> c = new ArrayList<Cow>();
		c.add(new Cow(0));
		//c.add(new Cow(1));
		Farm f = new Farm(c);
		f.product(20);

	}

	

	
	
}

class Cow {
	int age;

	public Cow(int age) {
		super();
		this.age = age;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	Cow giveBirth() {

		return new Cow(0);

	}

}

class Farm {

	public Farm() {
		super();
		this.cows.add(new Cow(0));
	}

	public Farm(Cow c) {
		super();
		this.cows.add(c);
	}

	public Farm(ArrayList<Cow> cows) {
		super();
		this.cows = cows;
	}

	ArrayList<Cow> cows = new ArrayList<Cow>();

	void product(final int year) {
		new Thread() {
			public void run() {
				for (int i = 0; i < year; i++) {
					for (int k =0;k < cows.size();k++  ) {
						
						cows.get(k).setAge(cows.get(k).getAge()+1);
						if (cows.get(k).getAge() >= 5) {
							Cow c = cows.get(k).giveBirth();
							cows.add(c);
						}
						
					}
					System.out.println((i+1)+" year past and the number of cows are " + cows.size());
					try {
						sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
		}.run();
	}
}

结果:

1 year past and the number of cows are 1
2 year past and the number of cows are 1
3 year past and the number of cows are 1
4 year past and the number of cows are 1
5 year past and the number of cows are 2
6 year past and the number of cows are 3
7 year past and the number of cows are 4
8 year past and the number of cows are 5
9 year past and the number of cows are 7
10 year past and the number of cows are 10
11 year past and the number of cows are 14
12 year past and the number of cows are 19
13 year past and the number of cows are 26
14 year past and the number of cows are 36
15 year past and the number of cows are 50
16 year past and the number of cows are 69
17 year past and the number of cows are 95
18 year past and the number of cows are 131
19 year past and the number of cows are 181
20 year past and the number of cows are 250


挺简单的算是给初学者吧

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值