看到一个题:农场一头老母牛,每年生头小母牛,母牛5岁生母牛,二十年上多少牛。 用面向对象的思维写。这是我的,但觉得不是很好,麻烦大家写个更好的
- package CowQuestion;
- import java.util.*;
- public class MainClass {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- List<Cow> cows=new ArrayList<Cow>();
- cows.add(new Cow(5));
- Farm f=new Farm(0,cows);
- f.past(20);
- f.countCow();
- }
- }
复制代码- package CowQuestion;
- import java.util.*;
- public class Farm{
- private List<Cow> cows;
- private int year;
- public List<Cow> getCows() {
- return cows;
- }
- public Farm(int year,List<Cow> cows) {
-
- this.cows = cows;
- this.year = year;
- }
- public void setCows(List<Cow> cows) {
- this.cows = cows;
- }
- public int getYear() {
- return year;
- }
- public void setYear(int year) {
- this.year = year;
- }
- public void countCow(){
- System.out.println("有"+cows.size()+"头牛");
- }
- public void past(int time) {
- while (this.year < time) {
- this.year++;
- for (int i = 0; i < cows.size(); i++) {
- Cow cow = cows.get(i);
- Cow calf = cow.growUp();
- if (calf != null) {
- cows.add(calf);
- }
-
- }
- }
- }
- }
复制代码- package CowQuestion;
- public class Cow {
- private int age;
- private final static int bearingAge=5;
- public Cow(int age) {
-
- this.age = age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getAge() {
- return age;
- }
- public Cow growUp(){
- age++;
- if(this.age>=bearingAge)
- return new Cow(0);
- return null;
- }
- }
复制代码
|