简体   繁体   English

如何跟踪哪个对象属于哪个对象?

[英]How to keep track of what object belongs to which object?

Disclaimer: This is a school project but Prof said it's ok to ask for help. 免责声明:这是一个学校项目,但教授表示可以寻求帮助。

The project is to simulate a traffic grid. 该项目是模拟交通网格。 The part I'm working on is keeping track of what car is on what road. 我正在研究的部分是跟踪什么车在什么道路上。 A road is an array list containing cars. 道路是包含汽车的数组列表。 I've made a road handler (an array list) that contains all roads. 我制作了包含所有道路的道路处理程序(数组列表)。

public void checkPositionOnRoad(){
    if(this.getPosition() > RoadHandler.currentRoad.getLength()-this.getCarLength()){
        RoadHandler.currentRoad.remove(this);
        Road nextRoad = moveToNextRoad(RoadHandler.currentRoad);
        nextRoad.accept(this);
    }
}

The problem is that I don't know how to keep track of "currentRoad". 问题是我不知道如何跟踪“ currentRoad”。 Getting the next road is easy enough because I can just say 走下一条路很容易,因为我只能说

nextroad(Road currentRoad); 

where I just grab the currentRoad's index+1. 在这里,我只是获取了currentRoad的index + 1。

The end goal is for the car to finish it's road and move on to the next one in the array of roads which RoadHandler keeps track off. 最终目标是让汽车完成其行驶的道路,并继续前进至RoadHandler跟踪的道路中的下一条。 So while the car runs it checks to see where its on in the road. 因此,在汽车行驶时,它会检查其在路上的位置。 Once it finishes it's road it takes itself out of the current Road and adds itself to the next one. 完成道路后,它将退出当前道路,并添加到下一条道路中。

public void run(double time) {
    checkPositionOnRoad();
    position += velocity;
}

Also I want to reset the car's position on the new road. 我也想重置汽车在新路上的位置。 The checkPositionOnRoad and run methods are in the Car class and the nextRoad method is in the RoadHandler class. checkPositionOnRoad和run方法在Car类中,nextRoad方法在RoadHandler类中。

Easy. 简单。 Create a POJO class to represent you cars objects. 创建一个POJO类来代表您的汽车对象。 And create an attribute in that class called currentRoad. 并在该类中创建一个称为currentRoad的属性。 Like this 像这样

String currenRoad;

The current road attribute should be changed each time you car enter to a new road. 每次您的汽车进入新道路时,都应更改当前道路属性。 it implies that you need to create a POJO class to represent you road objects. 这意味着您需要创建一个POJO类来表示您的道路对象。 Always remember design you problem before do coding 在进行编码之前,请务必记住设计问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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