package cow_farm; public class Test { /*农场一头小母牛, *每年生头小母牛, *母牛5岁产母牛, *20年上多少牛?--java面向对象方式实现 **/ public static void main(String[] args) { // TODO Auto-generated method stub Farm.getCows(20); } }
农场类:
1 package cow_farm; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class Farm { 7 8 private static List<Cow> cows; 9 static{ 10 cows =new ArrayList<>(); 11 Cow cow = new Cow(5); 12 cows.add(cow); 13 } 14 15 public static List<Cow> getCows(int year){ 16 for(int i=0;i<year;i++){ 17 List<Cow> tempCows =new ArrayList<Cow>(); 18 for(Cow cow:cows){ 19 tempCows.add(cow); 20 cow.setAge(cow.getAge()+1); 21 Cow xiaoCow = cow.sheng(); 22 if(xiaoCow != null){ 23 tempCows.add(xiaoCow); 24 } 25 } 26 cows = tempCows; 27 /*System.out.printf("第%d年奶牛数量:%d%n",i+1,cows.size());*/ 28 } 29 System.out.println("第"+year+"年奶牛的数量为"+cows.size()+"头"); 30 return cows; 31 } 32 33 }
母牛类:
1 package cow_farm; 2 3 public class Cow { 4 private int age; 5 6 public int getAge() { 7 return age; 8 } 9 10 public void setAge(int age) { 11 this.age = age; 12 } 13 14 public Cow(int age) { 15 super(); 16 this.age = age; 17 } 18 19 public Cow sheng(){ 20 if(age>=5){ 21 return new Cow(1); 22 }; 23 return null; 24 } 25 26 27 28 }
总结:1.发现自己的集合,这一块很模糊。
2.System.out.printf("第%d年奶牛数量:%d%n",i+1,cows.size())----中printf,println,print这三者的区别。%d是插数据,%n是换行(我的这是C++学过,好久不用忘了,多学习,多总结。)
3.java面向对象(封装,继承,多态)