我有10个通用代理:

public class Agent {
    private Context<Object> context;
    private Geography<Object> geography;
    public int id;
    public boolean isFemale;
    public double random;


public Agent(Context<Object> context, Geography<Object> geography, boolean isFemale, double random) {
    this.context = context;
    this.geography = geography;
    this.isFemale = isFemale;
    this.random = random;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public boolean isFemale() {
    return isFemale;
}

public void setFemale(boolean isFemale) {
    this.isFemale = isFemale;
}

public double getRandom() {
    return random;
}

public void setRandom(double random) {
    this.random = random;
}

public void methods  {

... does things
}


代理是在地理环境(纬度和经度)中创建的。我正在尝试将我的探员构造为随机的男性或女性。我在上下文生成器中用于创建代理的代码如下:

    Agent agent = null;
    boolean isFemale = false;
    for (int i = 0; i < 10; i++) {
        double random = RandomHelper.nextDoubleFromTo(0, 1);
        if (random > 0.33){
            isFemale = true;
        }
        agent = new Agent(context, geography, isFemale, random);
        context.add(agent);
        Coordinate coord = new Coordinate(-79.6976, 43.4763);
        Point geom = fac.createPoint(coord);
        geography.move(agent, geom);
    }


当我测试代码时,我发现它们都是女性。我究竟做错了什么?如果有的话,我会认为它们都是男性,因为默认情况下布尔值是false。

最佳答案

一旦boolean变为isFemale = true,它就不会为每个迭代更新。对于其他值,它仍然为true。您可以添加其他部分来将其设置为false

 for (int i = 0; i < 10; i++) {
        isFemale = false;//Set it here
        double random = RandomHelper.nextDoubleFromTo(0, 1);
        if (random > 0.33){
            isFemale = true;
            //...


要么

if (random > 0.33){
   isFemale = true;
} else {
   isFemale = false;
}


要么

agent = new Agent(context, geography, random > 0.33, random);

08-04 16:34