【发布时间】:2019-04-21 03:17:17
【问题描述】:
好的,伙计们,我是新来的,但在无数不同的场合使用该网站试图找到解决我遇到的问题的方法。我有一个正在为学校工作的汽车库存计划。本质上,我使用 setter 和 getter 将对象添加到我的汽车类中的 ArrayList。
我在编写 listAllVehicles 方法时遇到了很多麻烦。起初我可以在车辆数组列表中列出车辆,但它会给我一个指向该对象的指针。所以它看起来像 com.automobile@1662365。我想在汽车类中创建一个名为 listAllVehicles 的循环方法,该方法循环遍历数组列表并打印每个车辆的简短描述,直到列表完成。我在编写代码方面取得了一些进展,但它不起作用并且 for 循环没有初始化。我相信你们会知道我做错了什么。
我的代码目前没有设置为 ToString 方法来格式化打印的内容,但我对这个想法持开放态度(已经尝试但无法弄清楚)
任何帮助将不胜感激。谢谢大家!
我试图转换为字符串。我搞砸了在 for 循环中强制转换为一个对象。确实有很多不同的东西,但我似乎无法让这一切正常工作。
public static void main(String[] args) {
String model, make, color;
int year = 0;
int mileage = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("[1]Add a Vehicle\n[2]List All
Vehicles\n[3]Update a Vehicle\n[4]Delete a Vehicle\n[5]Quit\n");
System.out.print("Please choose from an option above: ");
int userChoice = userInput.nextInt();
switch(userChoice) {
case 1:
Scanner addVehicleScanner = new Scanner(System.in);
Automobile newVehicle = new Automobile();
System.out.print("What is the vehicle make: ");
make = addVehicleScanner.next();
newVehicle.setMake(make);
System.out.print("What is the vehicle model: ");
model = addVehicleScanner.next();
newVehicle.setModel(model);
System.out.print("What is the vehicle color: ");
color = addVehicleScanner.next();
newVehicle.setColor(color);
System.out.print("What is the vehicle year: ");
year = addVehicleScanner.nextInt();
newVehicle.setYear(year);
System.out.print("What is the vehicle mileage: ");
mileage = addVehicleScanner.nextInt();
newVehicle.setMileage(mileage);
newVehicle.addVehicle(newVehicle);
vehicleInventory.main(args);
break;
case 2:
Automobile printAllVehicles = new Automobile();
printAllVehicles.listAllVehicles();
break;
case 3:
//FIX ME: Add Update Vehicle Code
break;
case 4:
//FIX ME: Add Delete Vehicle Code
break;
case 5:
System.out.println("\n\nGoodbye!");
break;
public void listAllVehicles() {
Automobile temp = new Automobile();
for (int i = 0; i < vehicles.size(); i++) {
temp = (Automobile) vehicles.get(i);
System.out.println(temp);
}
}
【问题讨论】:
标签: java arrays object arraylist