Question: classical question: there is a rabbit. From the first 3rd months after birth, a rabbit is born every month. After the third month, a rabbit is born every month. If the Rabbit does not die, what is the total number of rabbits per month? Solution: using object-oriented thinking
Rabbit: there is only one field, that is, the number of months. One function is growth. It will be generated after three months.
Queue: Rabbit queue.
Okay, with the rabbit queue, just traverse the rabbits in every graph column. It can be long, and it can be baby-generated.
Code
Rabbit
Package Rubbot; import java. util. List; public class Rubbot {int eag = 0; // number of months public void grow (List
Allrobbout) {eag ++; // The number of months increases if (eag> = 3) // The number of months> 3, and generates the item {allrobbout every month. add (new Rubbot (); // The litter size is very simple. Just add a new rabbit to the rabbit queue }}}
Test Functions
Package Rubbot; import java. util. arrayList; import java. util. list; public class TestRobbot {public static void main (String [] args) {Rubbot r = new Rubbot (); // The first rabbit List
Allrobbot = new ArrayList
(); // Rabbit queue allrobbot. add (r); for (int I = 1; I <= 12; I ++) // 12 months a year {for (int j = 0; j
Calculation Result
1st month 1 only 2nd month 1 only 3rd month 2 only 4th month 3 only 5th month 5 only 6th month 8 only 7th month 13 only 8th month 21 only 9th month 34 only 10th month 55 only 11th-month 89 only 12th-month 144