我已经创建了我的课叫做汽车();我现在需要创建一个自动库存计划,以增加车辆,车辆打印的清单,删除车辆,并更新属性的方法。
我很困惑上,是我怎么调用构造函数来创建一个新的车,而接受用户输入构造对象,并在构造函数中的字段?
这是我的课:
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);
}
}
}
这不是印刷的实际列表:
你不必当实例它来定义汽车的所有属性。当您去,您可以设置其属性。举例来说,如果构造是这样的:
public AutoMobile(String color, String type) {
this.color = color;
this.type = type;
}
和你有一个属性,叫做manufacturer
,那么这是很好的定义部件private
或protected
:
private String manufacturer;
并定义一个getter和它二传手:
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
}