本帖最后由 ash午夜阳光 于 2015-11-6 23:49 编辑
package study;
public class Sheep {
public static void main(String[] args) {
for (int i = 1; i <= 21; i++) {
System.out.println("第" + i + "年,:" + (int) getSheepNum(i));
}
}
static int getSheepNum(double year) {
if (year == 0)// 第0年返回0
return 0;
else if (year == 1)// 第一年返回1
return 1;
else if (year <= 8)
return 2 * getSheepNum(year - 1);
else if (year == 9) {// 特殊因为8年前羊数为1,第9年,该羊得死,该年出生/2后为0,应该为1
return (getSheepNum(year - 1) - 1) * 2;
} else {
// 上年减去8年前出生的,以此为基数*2. 8年前出生的羊数为当年羊总数的一半
return (getSheepNum(year - 1) - (getSheepNum(year - 8) / 2)) * 2;
}
}
}尝试着用面向对象做了一下,不知那有问题运行结果和上面不一样,个人认为上面的应该没错.
不知面向对象到底应该怎么设计,有没有大神指点
package yang;
public class Sheep {
private int age;
public Sheep() {
this.age = 1;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/*********************************************************************************************/
package yang;
import java.util.ArrayList;
import java.util.List;
public class Sheeps {
int year;
List<Sheep> sheeps = new ArrayList<Sheep>();
public Sheeps() {
sheeps.add(new Sheep());
this.year = 1;
}
public void create() {
sheeps.add(new Sheep());
}
public void dead(Sheep s) {
sheeps.remove(s);
}
public void run(int y) {
for ( ; year < y; year++) {
int n = getSheepNum();
System.out.println(n);
// 每只羊的年龄+1
for (int j = 0; j < n; j++) {
Sheep s = (Sheep) sheeps.get(j);
s.setAge(s.getAge() + 1);
}
for (int k = 0; k < n; k++) {
Sheep s = (Sheep) sheeps.get(k);
if (s.getAge() > 8)
dead(s);
else
create();
}
}
}
public int getSheepNum() {
return sheeps.size();
}
}
/************************************************************************************/
package yang;
public class Test {
public static void main(String[] args) {
Sheeps sheeps = new Sheeps();
sheeps.run(21);
System.out.println(sheeps.getSheepNum());
}
}
|
|