2

我有一个代理类可以做一些事情:

public class Agent {


private Context<Object> context;
    private Geography<Object> geography;
    public int id;
    boolean female;

public Agent(Context<Object> context, Geography<Object> geography, int id, boolean female) {
    this.id = id;
    this.context = context;
    this.geography = geography;
    this.female = female;
}  

... setters getters
... do things methods

}

在上下文构建器类中,我的代理被添加到上下文(由纬度和经度坐标组成的地理空间)中,我想让我的代理的随机百分比为女性(女性 = true)。

for (int i = 0; i < 100; i++) {
        Agent agent = new Agent(context, geography, i, false);
        int id = i++;
        if(id > 50) {
            boolean female = true;  
        }
        context.add(agent);
        //specifies where to add the agent
        Coordinate coord = new Coordinate(-79.6976, 43.4763);
        Point geom = fac.createPoint(coord);
        geography.move(agent, geom);
    }

我相信上面的代码将最后 50 个代理构建为女性。我怎样才能使它们随机创建为女性?我改变了相当多的代理数量。

4

3 回答 3

2

使用您的代码,您总是可以创建一个男性代理。

在创建以下实例之前尝试评估它是否是女性Agent

Agent agent = null;
boolean isFemale = false;
for (int i = 0; i < 100; i++) {
        int id = i++;
        if(id > 50) {
            isFemale = true;
        }
        agent = new Agent(context, geography, i, isFemale);
        context.add(agent);
        //specifies where to add the agent
        Coordinate coord = new Coordinate(-79.6976, 43.4763);
        Point geom = fac.createPoint(coord);
        geography.move(agent, geom);
    }

如果您希望它是随机的,请尝试使用 Random 实用程序:

        Random random = new Random();
        agent = new Agent(context, geography, i, random.nextBoolean());

希望这可以帮助

于 2015-02-25T02:21:36.293 回答
0

您可以在 for 循环之外创建 Random 的单个实例,并使用 random.nextBoolean() 作为 agent() 的布尔女性属性的参数。

于 2015-02-25T02:36:21.947 回答
-1
        Random random = new Random();

        for (int i=0; i < 100; i++)
        {
            boolean isFemale = (random.Next(2) % 2 == 1);
            ...
        }
于 2015-02-25T02:21:59.053 回答