我是 Java 新手,最近编写了一个小程序,使用 Arraylist 将汽车存储在车库中。现在我必须将程序转换为仅使用数组。我的问题是我不能再像使用 Arraylist 那样直接引用我的 Car 类来创建一个 Array。
Car 类是在基于输入文件的 main 方法中创建的。
车类代码:
public class Car {
private final String licensePlate; // license plate number
private int timesMoved = 0; // number of moves car has endured
public Car(String licenseNum)
{
licensePlate = licenseNum;
}
public String getlicensePlate()
{
return licensePlate;
}
public void incrementTimesMoved() //increment number of moves by 1
{
timesMoved = timesMoved + 1;
}
public int getTimesMoved()
{
return timesMoved;
}
}
在我的车库课上,我有这个代码
public class Garage {
private Car carDeparted;
private ArrayList<Car> Garage; // a list of car objects
public Garage()
{
Garage = new ArrayList<>() ;
}
}
这真的很好,所以我用一个数组尝试了同样的想法,但没有做错
新车库类代码
public class Garage {
private Car carDeparted;
Car [] Garage; // a list of car objects
/**
Constructs a garage with no cars.
*/
public Garage()
{
Garage = new Car [10];
for (int i = 0; i < Garage.length; i++)
Garage[i] = new Car();
}
车库[i] = new Car(); 说错误,因为我需要字符串参数来填充它,但是当我有 arraylist 时,我没有这个问题。
我需要它,以便数组根据创建的汽车类在其中存储多达 10 辆汽车。
有任何想法吗?谢谢
德玛西亚99
蛊毒传说
慕尼黑8549860
相关分类