日期:2014-05-20 浏览次数:20757 次
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(); } }
------解决方案--------------------
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); } } }