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

あなたのコードでは、常に MALE のエージェントを作成します。

のインスタンスを作成する前に、それが女性かどうかを評価してみてください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 の単一のインスタンスを作成し、agent() の boolean female 属性のパラメーターとして random.nextBoolean() を使用できます。

于 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 に答える