我有一个项目是创建一个具有不同长度的数组aRoad。我需要通过这个数组移动元素并在它到达aRoad [N]后面的元素时最后删除该对象。
让我们假设: 我有许多对象("汽车")N和一个长度为L(= 4)的数组(" road")。
i = 0: car1 is at road[0].
i = 1: car1 is at road[1].
i = 2: car1 is at road[2], car2 spawns at road[0].
i = 3: car1 is at road[3], car2 is at road[1].
i = 4: car1 vanishes from the road, car2 is at road[2], car3 spawns at road[0].
我的汽车级:
package traffic;
public class Vehicle {
private int bornTime;
private char destination;
public Vehicle(int bornTime, char destination){
this.bornTime = bornTime;
this.destination = destination;
}
public int returnTime() {
return bornTime;
}
public char returnDest() {
return destination;
}
public String toString() {
System.out.print(destination);
return null;
}
}
我的问题是:一旦对象离开数组,我就会收到错误,因为索引超出范围。我尝试用IF条件来解决这个问题,并且由于第一个答案,我能够创建代码更新。
如何获得一个像Java一样运行的系统?我更新的方法:
public static void main(String[] args) {
int time = 1;
char[] aRoad = new char[6]; // lane length
Vehicle[] carList = {new Vehicle(1, 'X'), new Vehicle(4, 'Y')};
while(time < 15){
for(Vehicle car : carList){
if (car != null ){
int pos = time - car.returnTime();
if (pos >= 0){
if (pos >= 1){
aRoad[pos-1] = 0;
}
if (pos == (aRoad.length)){
aRoad[pos-1] = 0;
car = null;
}
if (car != null){
aRoad[pos] = car.returnDest();
}
}
}
}
//PRINT ARRAY EACH ITERATION, SET time = time + 1
}
输出如下:
[...]
time = 6: [ , , Y, , , X]
time = 7: [ , , , Y, , ]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at traffic.Test1.main(Test1.java:19)
所以我的具体问题是:
如果不将X-object(-car)设置为null
?
修改 由于这个问题太过不明确,我把所有无用的信息都丢掉了,整理了一下。
答案 0 :(得分:0)
我将回答你最明确的问题,答案应该为你指明正确的方向。
但我如何实际制造大量汽车?
您可能会因为尚未使用您的Vehicle对象的borntime
字段而陷入困境。对于你的while循环的每次迭代,应该通过
current time - borntime
因此,如果你有多个汽车和一个循环迭代你的时间维度
Vehicle car1 = new Vehicle(2, "X");
Vehicle car2 = new Vehicle(4, "Y");
...
int time = 2;
while(time < 10){
// calculate road positions
int car1Pos = time - car1.returnTime();
int car2Pos = time - car2.returnTime();
aRoad[car1Pos - 1] = 0;
aRoad[car1Pos] = car1.returnDest();
aRoad[car2Pos - 1] = 0;
aRoad[car2Pos] = car1.returnDest();
...
}
但是无论何时你的代码开始寻找这种重复,最好考虑更多的数组和循环。将车辆放入&#34;车辆阵列&#34;并在其上循环以更新每个车辆在阵列中的位置
Vehicle[] carList = {new Vehicle(2, "X"), new Vehicle(4, "Y")};
...
int time = 2;
while(time < 10){
for(Vehicle car : carList){
int pos = time - car.returnTime();
aRoad[pos-1] = 0;
aRoad[pos] = car.returnDest();
}
...
}
一旦你有了这个工作,下一步就是动态地将车辆添加到carList
,也许每两秒一次,并在它们到达路的尽头时从carList
移除它们。对ArrayList
carList
使用<xsl:for-each>
对于此部分会更容易。
请注意,我没有测试过这段代码,因此它们可能是语法错误。