我在名为Vehicle:
的抽象类中创建了一个名为idPlate的数组public abstract class Vehicle
{
String[] idPlate = new String[20];
public abstract void setIDPlate(String plate, int num);
public abstract String getIDPlate(int num);
}
我有另一个名为Car的类,它继承了Vehicle:
public class Car extends Vehicle
{
public void setIDPlate(String plate, int num)
{
idPlate[num] = plate;
}
public String getIDPlate(int num)
{
return idPlate[num];
}
}
我想从addVehicle方法写入CarParkManager类中的数组,并使用listVehicles方法从数组中打印:
public class CarParkManager
{
String returnToMenu = "Y";
String[] vehicle = new String[20];
public void menu()
{
while ("Y".equals(returnToMenu)) {
System.out.println("*********Menu*********");
System.out.println("Type appropriate number to select option:");
System.out.println("1- Add new vehicle to Car Park");
System.out.println("3- List Vehicles in Car Park");
Scanner scan = new Scanner(System.in);
String listnumber = scan.nextLine();
if ("1".equals(listnumber)) {
addVehicle(vehicle);
}
if ("3".equals(listnumber)) {
listVehicles(vehicle);
}
}
}
private void addVehicle(String v[])
{
System.out.println("Enter car ID plate");
Scanner input = new Scanner(System.in);
String vehicleid;
vehicleid = input.nextLine();
for (int x = 0; x < v.length; x++) {
if (v[x] == null) {
v[x] = "Car";
Car car = new Car();
car.setIDPlate(vehicleid, x);
break;
}
}
}
public void listVehicles(String v[])
{
System.out.println("****List Vehicle in Car Park****");
for (int x = 0; x < 20; x++) {
if (v[x] == null) {
System.out.println("Parking lot " + x + ": Vacant");
}
if (v[x] == "Car") {
Car getcarid = new Car();
System.out.println("Parking lot " + x + ": " + v[x] + ", ID-" + getcarid.getIDPlate(x));
}
}
}
}
我可以从车辆阵列中打印出来,但是idPlate保持为空,因此输出如下: 停车场0:Car,ID-null
答案 0 :(得分:0)
你做
Car car = new Car(); // create a new Car
car.setIDPlate(vehicleid, x);
// don't do anything with it, throw it away
和
Car getcarid = new Car(); // create a new uninitialised car.
// try to print the uninitialised car.
System.out.println("Parking lot " + x + ": " + v[x] + ", ID-" + getcarid.getIDPlate(x));
我怀疑你打算创建一个Car对象,你首先在一个方法中设置并在另一个方法中打印出来。我建议将Car对象传递给每个方法。
答案 1 :(得分:0)
我相信你在调用getIDPlate之前没有调用setIDPlate方法。此外,我发现没有一段代码初始化idPlate,因此idPlate中的所有字符串都是defult的null。我希望这有帮助。