【发布时间】:2016-11-30 15:57:44
【问题描述】:
我有一个项目是创建一个长度不同的数组 aRoad。我需要通过这个数组移动元素并最终删除对象,当它到达aRoad [N]后面的元素时。
让我们假设: 我有许多对象(“汽车”)N 和一个长度为 L(=4)的数组(“道路”)。
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 对象 (-car) 设置为 null 的情况下防止此异常?
编辑 由于问题太不明确,我把所有无用的信息都扔掉了,整理一下。
【问题讨论】:
-
您的问题到底是什么?现在它有被关闭的危险,因为它基本上太宽泛了。
-
好的,更具体一点:例如,我需要每 2 秒构建一个 Vehicle 类的汽车。然后这些汽车将通过名为 road 的数组移动并在到达终点时被删除:a)我如何创建和标记例如 5 辆汽车?以及如何通过检查数组 [i+1] 是否未被占用来移动位置,以及,b) 如何在到达数组 [end] 时删除每辆车。是不是更具体?
-
是的,这是特定的,也是 Java 基础。将自己限制在一个问题上,然后发布您在该问题上的当前进展。