计算物种的增长率

时间:2014-09-15 06:21:16

标签: java

我必须根据物种的增长率增加人口,即更新人口实例变量。但我不确定我在这里需要做什么。

public void grow() {

}

以下是我的其余代码。

public class Species {  

    public String name;
    public int populations;
    public double growthRate;

public Species (String name, int populations, double growthRate){
    this.name = name;
    this.populations = populations;
    this.growthRate = growthRate;
}

public void mergeSpecies(Species other){
    // add population
    this.populations += other.populations;
    // concatenation of the two names
    this.name += other.name;
    // maximum of the two growth rates
    if (this.growthRate > other.growthRate){
        this.growthRate = this.growthRate;
    }
    if (this.growthRate < other.growthRate){
        this.growthRate = other.growthRate;
    }
}

public String toString(){
    String output = "";
    output += "Name: " + this.name + "\n";
    output += "Population: " + this.populations + "\n";
    output += "Growth Rate: " + Math.round(this.growthRate) + "%" + "\n";
    return output;
}


public void grow() {

}

public int populationInXYears(int x){
    int result = 0;
    double population = this.populations;
    int count = x;
    while ((count > 0) && (population > 0)){
        population = population + (this.growthRate / 100) * population;
        count--;
    }
    if (population > 0){
        result = (int)population;
    }
    return result;
}

}

4 个答案:

答案 0 :(得分:1)

由于您已经拥有 populationInXYears()函数,该函数会在一定年限后为您提供人口,因此您可以使用1调用它来获取一个年:

public void grow() {
    populations = this.populationInXYears(1);
}

这样,它遵循与您已有的相同的规则,关于人口降至零以下(即,它可以&#39;)。

答案 1 :(得分:0)

假设growthRate是每次迭代时群体应该增长的速率,并假设它表示为分数:

public void grow() {
    populations = (int) (populations * (1.0 + growthRate);
}

答案 2 :(得分:0)

public void grow() {
    this.populations *= (1+growthRate/100.0);
}

用当前人口*覆盖实例变量*新人口的增长率。

答案 3 :(得分:0)

你自己写过这部分populationInXYears吗?

while ((count > 0) && (population > 0)){
    population = population + (this.growthRate / 100) * population;
    count--;
}

看起来您的grow()方法应该包含人口变化:

public void grow() {
    population = population + (this.growthRate / 100) * population;

    // There can't be a negative population.
    if(population < 0) {
        population = 0;
    }
}

因此您可以将循环更改为:

while ((count > 0) && (population > 0)){
    grow();
    count--;
}

这样,您可以单独调用grow()以立即增长,或populationInXYears增长X年。