我有一种方法可以为vehicles阵列增加一辆新车(本田).该阵列最多包含4辆车.
Vehicle[] vehicles = new Vehicle[4];
Run Code Online (Sandbox Code Playgroud)
如果存在值,则该方法应该将1个新Vehicle对象添加到vehicles数组的末尾null.问题是它正在写入null数组中的所有值,而不是只写入1然后踢出for循环.
这就是我所拥有的(注意 - 我需要使用数组代替ArrayList):
public void addVehicle(Vehicle Honda[]) throws FileNotFoundException
{
boolean found = false;
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length || !found; i++)
{
if(vehicles[i] == null)
{
Scanner reader = new Scanner(file);
Honda[i] = new Vehicle();
Honda[i].readRecord(reader);
vehicles[i] = Honda[i];
reader.close();
found = true;
}
}
System.out.println("Vehicle Added!");
}
}
Run Code Online (Sandbox Code Playgroud)
我设置found = true为确保它一旦找到null数组中的第一个值就离开for循环..但它似乎没有工作.为什么会这样?
编辑:此外,我不允许有任何其他类级数据.
您在使用||时正在使用&&:
for(int i = 0; i < vehicles.length && !found; i++)
Run Code Online (Sandbox Code Playgroud)
有关条件运算符的更多信息,请参阅此Java教程文章.
作为一个友好的批评,这对另一个开发人员来说是不可读的.以下将更容易遵循:
for(int i = 0; i < vehicles.length; i++)
{
if(vehicles[i] == null)
{
Scanner reader = new Scanner(file);
Honda[i] = new Vehicle();
Honda[i].readRecord(reader);
vehicles[i] = Honda[i];
reader.close();
break; //break out of the loop
}
}
Run Code Online (Sandbox Code Playgroud)