不死神兔,面向对象思想,直观通俗易懂

有一只兔子,从出生后第3个月起每个月都生只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?

public class CalculateRabbit{
    public static void calculate(int month, List rabbits, List extRabbits) {
        if (month > 12) {
            return;
        }
        for (Rabbit rabbit : rabbits) {
            if (rabbit.getMonth() >= 3) {
                Rabbit extRabbit = new Rabbit();
                extRabbit.setMonth(extRabbit.getMonth() + 1);
                extRabbits.add(extRabbit);
            }
            rabbit.setMonth(rabbit.getMonth() + 1);
        }
        rabbits.addAll(extRabbits);
        extRabbits.clear();
        System.out.println("第" + month + "月有" + rabbits.size() + "只兔子");
        month++;
        calculate(month, rabbits, extRabbits);
    }

    public static void main(String[] args) {
        List rabbits = new ArrayList();
        rabbits.add(new Rabbit());
        List extRabbits = new ArrayList();
        calculate(1, rabbits, extRabbits);
    }
}

class Rabbit {
    private int month = 1;

    public int getMonth() {
        return this.month;
    }

    public void setMonth(int month) {
        this.month = month;
    }
}

你可能感兴趣的:(不死神兔,面向对象思想,直观通俗易懂)