母牛问题(非算法解答)

java 代码
 
  1. import java.util.ArrayList;  
  2.   
  3. /** 
  4.  * 牛产仔问题。有一头母牛,它每年年初要生一头小母牛;每头小母牛从第四个年头起, 
  5.  * 每年年初也要生一头小母牛。按此规律,若无牛死亡,第20年头上共有多少头母牛? 
  6.  * 
  7.  * @author  
  8.  */  
  9. public class Mooooo {  
  10.   
  11.     public static void main(String[] args) {  
  12.         ArrayList<cow> cows = new ArrayList<cow>(); </cow>// 牛群(冯巩不在)  </cow>
  13.         cows.add(new Cow(3));  
  14.   
  15.         for (int i = 0; i < 20; i++) {  
  16.             ArrayList<cow> newCows = new ArrayList<cow>(); </cow>// 小牛群  </cow>
  17.             for (Cow cow : cows) {  
  18.                 cow.happyBirthday(newCows);  
  19.             }  
  20.             cows.addAll(newCows);  
  21.         }  
  22.   
  23.         System.out.println("二十年光阴似箭,共有牛 " + cows.size() + " 头。");  
  24.     }  
  25.   
  26.     /** 
  27.      * 母牛 
  28.      */  
  29.     static class Cow {  
  30.         private int age = 0;  
  31.   
  32.         public Cow(int age) {  
  33.             this.age = age;  
  34.         }  
  35.   
  36.         public void happyBirthday(ArrayList<cow> cows) {  </cow>
  37.             age++;  
  38.             if (age >= 3) {  
  39.                 cows.add(new Cow(0));  
  40.             }  
  41.         }  
  42.     }  
  43. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值