- /*
- */
- package cn.yy.practice;
- import java.util.*;
- /**
- * 既然母牛生小牛,就用Cow类代表牛,提及时间,用年龄age表示,刚出生age=0.
- * 还应该提供一个bear()方法,返回一个新的Cow对象,表示生了一头牛.
- * 使用List集合来存储所有的牛,每遍历一次,表示过了一年,增加一个变量currentYear表示当前年份
- * 遍历过程中,判断每个Cow的age值,如果大于或等于3,生育一头小牛,并将这头小牛也存入集合
- * 遍历后增加一个变量currentCount记录当前集合中总共有多少Cow对象
- * 最后返回currentCount,表示指定年份n后总共有多少牛.
- */
- public class CowProblem {
-
- List<Cow> cows = new ArrayList<Cow>(); //每生一头牛,存入集合
- public int count(int year){ //指定年份
- int currentYear = 0; //当前年份
- cows.add(new Cow()); //加入第一头母牛
-
- int currentCount = cows.size(); //当前集合中元素个数.
-
- while((currentYear++) < year ){
- for (int i=0; i<currentCount; i++ )
- {
- Cow c = cows.get(i); //取出一个Cow对象,并将年龄加1
-
- if(++c.age >= 3) //如果大于或等于3,则产生一个新Cow对象,并存入集合
- cows.add(c.bear());
- }
- currentCount = cows.size(); //每次遍历后记录下当前集合内的元素个数,
- //防止下一次遍历过程中,遍历到了新产生的牛
- }
-
- return currentCount;
-
- }
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("input an integer(year) : ");
- int year = 0;
- int sum = 0;
- try{
- year = input.nextInt(); //指定年份
- if(year >= 0)
- sum = new CowProblem().count(year);
- System.out.println("cow count = " + sum); //打印结果
- }catch(InputMismatchException e){
- System.out.println("not an integer, or is out of range");
- }
-
-
- }
-
- }
- class Cow { //定义一个Cow类,
-
- int age;
- public Cow(){ //初始化age
- age = 0;
- }
- public Cow bear(){ //bear()方法,返回一个新的Cow对象,表示生了一头牛.
- return new Cow();
- }
- }
复制代码 |
|