牛生牛的问题
来源:互联网 发布:nvslp监控软件下载 编辑:程序博客网 时间:2024/06/08 05:48
以前记得在学习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 blocke.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
挺简单的算是给初学者吧
- 牛生牛的问题
- 问题背后的问题
- 关于问题的问题
- 问题背后的问题
- 有问题的问题?.?
- 的问题
- 问题++: firefox的关闭问题
- 问题:input类型的问题
- 百鸡问题的问题
- 5.4 关于问题的问题
- 优化问题的对偶问题
- [问题]AS的问题集锦
- “存钱问题”遇到的问题
- 牛生牛问题
- 牛生牛的问题,假如生出来的都是母牛
- 求伯君的问题还是记者的问题?
- StoreAccess的问题【datasource的问题】
- 奇怪的问题(关于数据库的问题)
- AndEngine学习笔记(三)
- 第八周任务二 运算符重载 计算时间
- windows phone 加速计
- sql查询语句——单表查询
- ajax====xmlHttpRequest对象的常用属性和方法
- 牛生牛的问题
- 各大IT公司2012校园招聘笔试面试整理--解题报告整理
- android canvas类
- linux常用命令
- window.onload的加载时间
- RAC上 read by other session 解决一例
- UICatalog 随手记
- 学习OpenCV——SVM
- 字符串中字符'\0'是二进制值为零