题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
要求输入月数可以显示本月的兔子数
------解决方案--------------------
这种是非正常做法,正常做法是递归,哥们。。。我都解释是模拟了。
- Java code
import java.util.ArrayList;import java.util.List;class Rabbit{ int age; public Rabbit(){ this.age=1; } public boolean createBaby(){ age++; if(age>=3){ return true; } else{ return false; } }}public class Home implements Runnable{ static List<Rabbit> lr; int countOfMonth = 0; public Home(int com){ this.countOfMonth = com; Rabbit r = new Rabbit(); lr = new ArrayList<Rabbit>(); lr.add(r); } @Override public void run(){ int count=0; while(count<countOfMonth){ System.out.println(lr.size()); try { Thread.sleep(1000); count++; } catch (InterruptedException e) { e.printStackTrace(); } int newBabyCount=0; for(Rabbit r:lr){ if(r.createBaby()){ newBabyCount++; } } for(int i=1;i<=newBabyCount;i++){//不好意思,刚才数据并发了。 lr.add(new Rabbit()); } } } public static void main(String args[]){ Home h = new Home(10); new Thread(h).start(); }}
------解决方案--------------------
- Java code
package com;import java.util.Scanner;public class Rabbit { public static void main(String[] args) { Rabbit rabbit = new Rabbit();// for(int i = 1; i <= 12; i++) {// System.out.println(i + ":" + rabbit.getRabbitCount(i));// } Scanner scanner = new Scanner(System.in); System.out.print("请输入月数(当输入为0的时候结束):"); while(true) { try { String str = scanner.nextLine(); int x = Integer.parseInt(str); if(x == 0) { //System.exit(0); break; } System.out.println(x + ":" + rabbit.getRabbitCount(x)); } catch(Exception e) { System.out.println("你输入的不是正整数"); } } } public int getRabbitCount(int month) { if(month < 1) { throw new IllegalArgumentException(); } if(month == 1 || month == 2) { return 1; } else { return this.getRabbitCount(month - 1) + this.getRabbitCount(month - 2); } }}