23,404
社区成员
发帖
与我相关
我的任务
分享
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class CountCow {
/**
* @author lyp
* @param args
* @description :设有一头小母牛,从出生第四年起每年生一头小母牛,按此规律,第N年时有几头母牛?
*/
public static void main(String[] args) {
int N=10;//N年后,先把N设为10吧;
List<Cow> totalCows=new LinkedList<Cow>();//list集合类,用来装牛的总数
List<Cow> addCows4everyYear=new LinkedList<Cow>();//每年增加的牛;
Cow c1=new Cow();//最开始的那头母牛
totalCows.add(c1);//添加进去总数
/**
* for()循环
* 从第一年起,到第N年;看看每年牛的情况
*/
for(int i=1;i<=N;i++){
Iterator<Cow> it=totalCows.iterator();
//迭代,把一个个小牛找出来,看看能不能生孩子;
while(it.hasNext()){
Cow c=it.next();
c.giveBirthToBabyCow(addCows4everyYear);//生孩子,不一定能生,只有年龄大于4的就能生,逻辑判断封装在方法内部
c.AgeIncrease();//又长大了一年
}
/**
* 输出一些友好提示信息,看看每年是否有小牛出生,有多少个?
*/
if(addCows4everyYear.size()>0){
System.out.println(" ---------第"+(i)+"年"+"生下"+addCows4everyYear.size()+"个小牛");
}else{
System.out.println(" !!!!!第"+(i)+"年没生下小牛");
}
//把每年出生的所有小牛添加到总数去;
totalCows.addAll(addCows4everyYear);
//当然,添加进去了,这边就要清空啦
addCows4everyYear.clear();
}
//N年了,来数一数总共有多少个头牛吧
System.out.println("统计结果:::::::"+N+"年后有"+totalCows.size()+"头牛");
}
}
/**
* 这个类是表示牛,单词拼写错误了没?
* @author Administrator
*
*/
class Cow{
private int age=0;//年的年龄
/*
* 这方法表示牛长大一岁
*/
public void AgeIncrease() {
this.age++;
}
public int getAge() {
return age;
}
/*
* 这个方法表示牛生一个孩子,如果牛的年龄大于4岁,就能当妈妈咯
*/
public void giveBirthToBabyCow(List<Cow> list){
if(this.age>=4){
list.add(new Cow());
}
}
}
public class CountCow {
public static void main(String[] args) {
int counts = CountCow.count(new Cow(), 8);
System.out.println(counts);
}
public static int count(Cow cow, int years){
if(years < 0 || cow == null) throw new RuntimeException("");
for(int i = 1; i <= years; i++){
cow.grow();
cow.calve();
}
return cow.countAllChilds();
}
}
public class Cow {
private int age = 0;
private List<Cow> childs = new ArrayList<Cow>();
private static final int GROW_UP_AGE = 4;
public int getAge() {
return age;
}
public List<Cow> getChilds() {
return childs;
}
public void grow(){
age++;
childsGrow(this);
}
public void calve(){
if(age >= GROW_UP_AGE){
childs.add(new Cow());
}
childsCalve(this);
}
public int countAllChilds() {
return count(this);
}
private int count(Cow cow){
int result = 1;
if(cow == null) return 0;
if(cow.getChilds().size() == 0) return 1;
for(Cow child : cow.getChilds()){
result += count(child);
}
return result;
}
private void childsGrow(Cow cow) {
if(cow == null) return;
if(cow.getChilds().size() == 0) return;
for(Cow child : cow.getChilds()){
child.grow();
}
}
private void childsCalve(Cow cow) {
if(cow == null) return;
if(cow.getChilds().size() == 0) return;
for(Cow child : cow.getChilds()){
child.calve();
}
}
}