2

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 であるため、すべて男性であると思います。

4

2 に答える 2

2

繰り返しbooleanごとに更新するのではなくisFemale = true、他の値についても true のままになります。else 部分を追加して設定することができます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);
于 2015-02-26T00:53:00.350 に答える
1

ブール値が true に設定されると、そのままになるためです (false に設定することはありません。if の 1 つのブランチにすぎません)。

ところで、質問のタイトルをキャッチ

于 2015-02-26T00:49:20.180 に答える