// * 牛产仔问题。有一头母牛,它每年年初要生一头小母牛;每头小母牛从第四个年头起, //* 每年年初也要生一头小母牛。按此规律,若无牛死亡,第20年头上共有多少头母牛? public class CowCount { public static void main(String[] args) { int year = 20; ArrayList<Cow> cows = new ArrayList<Cow>(); cows.add(new Cow(3)); for (int i = 0; i < year; i++) { ArrayList<Cow> newCows = new ArrayList<Cow>(); for (Cow cow : cows) { cow.haveBirthday(newCows); } cows.addAll(newCows); } System.out.println(year + "年光阴似箭,共有牛" + cows.size() + "头。"); } } class Cow { private int age = 0; public Cow(int age) { this.age = age; } public void haveBirthday(ArrayList<Cow> cows) { age++; if (age > 3) { cows.add(new Cow(0)); } } }