Java练习 经典的兔子问题

好久没写Java代码,太生疏了。找些练习做做,温故而知新 - 递归很实用。


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值