不死神兔,面向物件思想,直觀通俗易懂
阿新 • • 發佈:2018-12-16
有一隻兔子,從出生後第3個月起每個月都生只兔子,小兔子長到第三個月後每個月又生一隻兔子,假如兔子都不死,問每個月的兔子總數為多少?
public class CalculateRabbit{ public static void calculate(int month, List<Rabbit> rabbits, List<Rabbit> 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<Rabbit> rabbits = new ArrayList<Rabbit>(); rabbits.add(new Rabbit()); List<Rabbit> extRabbits = new ArrayList<Rabbit>(); calculate(1, rabbits, extRabbits); } } class Rabbit { private int month = 1; public int getMonth() { return this.month; } public void setMonth(int month) { this.month = month; } }