我有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);
}
当我测试代码时,我发现他们都是女性。我究竟做错了什么?如果有的话,我会认为他们都是男性,因为布尔值默认为假。
答案 0 :(得分:2)
boolean
一旦变为isFemale = 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;
}
<强> OR 强>
agent = new Agent(context, geography, random > 0.33, random);
<强> OR 强>
{{1}}
答案 1 :(得分:1)
因为一旦你的布尔值设置为true,它就会保持这种状态(你永远不会将它设置为false,它只是if的一个分支)。
BTW,抓问题标题