简体   繁体   中英

What is wrong with my loop?

I have a list (boxlist) of 6 boxes, each with a count of 1 object per box (num_objects). Each box exists in a geography context (are located at specific latitude and longitude coordinates):

    //iterate through each of the boxes in the list (6)
    for (int i = 0; i < boxlist.size(); i++){
        //get the first box... then second box... etc (call it target box)
        Box targetbox = boxlist.get(i);
        Context context = ContextUtils.getContext(targetbox);
        Geography<Object> geography = (Geography)context.getProjection("Geography");
        Geometry geom = geography.getGeometry(targetbox);
        //get the coordinates of the target box
        Coordinate coord = geom.getCoordinates()[0];

        //for each of the 6 boxes, get the number of objects in the target box
        double num = targetbox.getNum_objects();
        // print the number of objects in each box (1)
        System.out.println(num);

        //create random utility
        Random random = new Random();
        // create the same number of BoxObjects as the num_objects in the box and place them in the geography at the same location as the box they are in (take them out of the box)
        for (int j = 0; j < num; j++) {
            boolean randomBoolean = random.nextBoolean();
            boolean anotherBoolean = false;
            BoxObject obj = new BoxObject(context, geography, randomBoolean, anotherBoolean);
            context.add(obj);
            // move to the object to the same coordinates of its box
            geography.move(obj, new GeometryFactory().createPoint(coord));
        }   

  } 

My loop is correctly counting that there are 6 boxes with 1 object in the box which should create 6 objects, but its creating 12 objects. How can I fix this?

Note: in the actual simulation, boxes may have more than one object.

My problem was that this code was nested in an Agent class. I had two Agents and it was running the method twice, once for each agent (producing double the objects). When I moved this code to the main model class (since technically it doesn't have anything to do with the agents), it worked perfectly.

You have a targetbox with an object in it. Box targetbox = boxlist.get(i);

You also get the context of the targetbox that has an object in it. Context context = ContextUtils.getContext(targetbox);

You then add another object to that same context. Whatever BoxObject does, as you pass it the context, it should remove previous objects from the context so that you only have the newly created object(s) in the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM