好久没写Java代码,太生疏了。找些练习做做,温故而知新 -
递归很实用。
class="java" name="code">
package edu.rob.prac;
import java.util.LinkedList;
/**
*
* 【程序1】
* 题目:古典问题:有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一
* 只兔子,假如兔子都不死,问每个月的兔子总数为多少?
*
*/
public class Practice_001 {
public static void main(String[] args) {
// Check each amount of all rabbits for the 1st to 10th month
for(int currentMonth=1; currentMonth<=10; currentMonth++) {
Rabbit r = new Rabbit(1);
r.setDirectChildren(currentMonth);
System.out.println("The " + currentMonth + " Month : " + r.getFamilyMemebersAmt());
}
}
}
class Rabbit {
private int birthday;
private LinkedList<Rabbit> directChildren = new LinkedList<Rabbit>();
public Rabbit() {}
public Rabbit(int birthday) {
this.birthday = birthday;
}
// Set direct children base on current month and birthday of this rabbit
public void setDirectChildren(int currentMonth) {
Rabbit r;
int month = currentMonth;
// Add direct children if it has
while ( month - this.birthday > 1) {
r = new Rabbit(month);
r.setDirectChildren(currentMonth);
this.directChildren.add(r);
month--;
}
}
// get amount of all children and this rabbit
public int getFamilyMemebersAmt() {
int familyMembersAmt = 1;
for(Rabbit r:this.directChildren) {
familyMembersAmt += r.getFamilyMemebersAmt();
}
return familyMembersAmt;
}
/**
* @return the directChildren
*/
public LinkedList<Rabbit> getDirectChildren() {
return this.directChildren;
}
/**
* @param directChildren the directChildren to set
*/
public void setDirectChildren(LinkedList<Rabbit> children) {
this.directChildren = children;
}
/**
* @return the birthday
*/
public int getBirthday() {
return birthday;
}
/**
* @param birthday the birthday to set
*/
public void setBirthday(int birthday) {
this.birthday = birthday;
}
}
下面是程序运行结果。
The 1 Month : 1
The 2 Month : 1
The 3 Month : 2
The 4 Month : 3
The 5 Month : 5
The 6 Month : 8
The 7 Month : 13
The 8 Month : 21
The 9 Month : 34
The 10 Month : 55