用构造函数将车辆添加到数组列表

时间:2019-02-01 19:28:12

标签: java arraylist constructor

我创建了名为AutoMobile()的类;现在,我需要为自动库存计划创建方法,以添加车辆,打印车辆列表,移除车辆并更新属性。

我感到困惑的是,当我接受构造函数对象和构造函数中的字段的用户输入时,如何调用构造函数来创建新车?

这是我的课程:

public class AutoMobile {

//initialize private variables
private String make;
private String model;
private String color;
private int year;
private int mileage;

public AutoMobile() {
    this("Default make", "Default model", "Default color", 2019, 0);
    System.out.println("Empty constructor called");
}

public AutoMobile(String make, String model, String color, int year, int mileage) {
    this.make = make;
    this.model = model;
    this.color = color;
    this.year = year;
    this.mileage = mileage;
}

我能够做到这一点,所以我可以将列表放在主要位置。但是,我在如何打印列表内容方面遇到了困难。

public class Main {


public static AutoMobile addAuto(List<AutoMobile> autoInventory) {
    Scanner addCar = new Scanner(System.in);

    System.out.println("Enter Vehicle Make: ");
    String make = addCar.nextLine();

    System.out.println("Enter Vehicle Model: ");
    String model = addCar.nextLine();

    System.out.println("Enter Vehicle Color: ");
    String color = addCar.nextLine();

    System.out.println("Enter Vehicle Year: ");
    int year = addCar.nextInt();

    System.out.println("Enter Vehicle Mileage: ");
    int mileage = addCar.nextInt();

    AutoMobile car =  new AutoMobile(make, model, color, year, mileage);

    autoInventory.add(car);

    addCar.close();

  return car;


}

public static void removeAuto() {
    //todo will be used to remove auto from invetory list

}

public static void printVehicles(List<AutoMobile> autoInventory) {
    //todo allows user to print inventory lsit

}

public static void updateAttributes() {
    //todo allows user to update attribute of specific vehicle

}


public static void main(String[] args) {
    List<AutoMobile> autoInventory = new ArrayList<AutoMobile>();

   AutoMobile newCar = (addAuto(autoInventory));

    for (AutoMobile val: autoInventory) {
        System.out.println(val);

    }



}

}

它不是打印实际列表:

enter image description here

1 个答案:

答案 0 :(得分:0)

实例化汽车时,不必定义汽车的所有属性。您可以随时设置其属性。例如,如果构造函数如下所示:

public AutoMobile(String color, String type) {
    this.color = color;
    this.type = type;
}

和你有称为属性manufacturer,则这是很好的限定构件privateprotected

private String manufacturer;

并为其定义一个getter和setter:

public String getManufacturer() {
    return manufacturer;
}

public AutoMobile setManufacturer(String manufacturer) {
    this.setManufacturer = manufacturer;
    return this; //You can chain setters this way, but the method can be void as
    //well if that's your preference
}