用Java程序写出 农场有一头母牛,每年生一头小母牛,小牛5岁可生小牛,20年后有多少头牛

2020-04-28 教育 115阅读
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
List cows = new ArrayList();
Cow curCow = new Cow();
curCow.setAge(5);
cows.add(curCow);
System.out.println(cows.size());
for (int i = 1; i <= 20; i++) {
for (int j = 0; j < cows.size(); j++) {
curCow = cows.get(j).getCow();
if(null!=curCow)
cows.add(curCow);
}
}
System.out.println(cows.size());
}
}
class Cow{
private int age = 1;
public Cow getCow(){
if(age<5){
this.age++;
return null;
}
this.age++;
return new Cow();
}
public void setAge(int age){
this.age = age;
}
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com