gpt4 book ai didi

java - 从无孔阵列中移除

转载 作者:行者123 更新时间:2023-12-02 05:51:47 24 4
gpt4 key购买 nike

我有一个 CarArray,其中包含 Car 对象,并且我已经在获取的方法上停留了一段时间了一个汽车号码,需要删除所有具有该汽车号码的对象,然后返回该数组,没有任何漏洞。这是我的作业,所以我不能使用任何 arrayListArray. 方法。

我尝试执行以下操作,但由于某种原因,当我尝试运行它时,它不符合要求,并给我一个 IndexOutOfBounds 错误,并请我引用我的 toString 方法(它打印数组中的所有单元格)。

noOfCars,保存当前实际的汽车数量,因为我们使用容器构造函数构建了数组,以便为​​ future 的汽车保留更多位置,以防万一。

public void removeCarNumbers(int CarNum) {
int count = 0;
for(int i = 0; i < this.noOfCars; i++) {
if(this.cars[i].getCarNum() == CarNum) {
this.cars[i] = this.cars[noOfCars- 1 - count];
count++;
}
}
CarsLines [] newArr = new CarLines[this.noOfCars- count];

for(int i = 0; i< this.noOfCars - count; i++)
{
newArr[i] = this.cars[i];
}
this.cars= newArr;
}

*编辑:在玩了更多之后,我仍然收到一个错误,将我引向我的 toString() 方法。它也有问题吗? 公共(public)字符串 toString() { 字符串输出=“”; for (int i = 0; i < this.noOfCars; i++) 输出 += ""+ this.cars[i].toString() + "\n"; 返回输出; }

最佳答案

尝试:

// count
int count = 0;
for(int i = 0 ; i < this.cars.length ; ++i) {
if(this.cars[i].getCarNum() == CarNum) {
++count;
}
}
// create new array
CarsLines[] newArr = new CarLines[this.cars.length - count];
int index = 0;
for(int i = 0 ; i < this.cars.length ; ++i) {
if(this.cars[i].getCarNum() != CarNum) {
newArr[index++] = this.cars[i];
}
}
// assign
this.cars = newArr;

关于java - 从无孔阵列中移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23474159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com