gpt4 book ai didi

java - 将对象从另一个类添加到 ArrayList

转载 作者:行者123 更新时间:2023-11-30 08:29:05 28 4
gpt4 key购买 nike

我对编程还很陌生,目前正在尝试编写一个汽车展厅应用程序。我有一个车辆类、陈列室类,我正在尝试使用陈列室驱动程序进行输入。

我在将车辆对象添加到数组列表时遇到问题。有人能指出我正确的方向吗。

我的代码:

public class Vehicle {

private String manufacturer;
private String model;
private String custName;
private String vin;
private String dateMan;
private String dateSold;
private Boolean sold;
private char tax;
private double cost;

public Vehicle(String a, String b, String c, String d) {
manufacturer = a;
model = b;
vin = c;
dateMan = d;
}

public String toString() {
String s = "Manufacturer: " + manufacturer + " Model: "
+ model + " vin: " + vin + "Date Manufactured:" + dateMan
+ "Cost: " + cost;
return s;
}

public void buyVehicle(String a, String b) { //buy method for the vehicle
a = dateSold;
b = custName;
sold = true;
}

public String getManufacturer() {
return manufacturer;
}

public String getModel() {
return model;
}

public String getCustName() {
return custName;
}

public String getVin() {
return vin;
}

public String getDateMan() {
return dateMan;
}

public String getDateSold() {
return dateSold;
}

public Boolean getSold() {
return sold;
}

public char getTax() {
return tax;
}

public double getCost() {
return cost;
}
}

.

import java.util.ArrayList;

public class Showroom {

private ArrayList<Showroom> theVehicles;

public Showroom() {
theVehicles = new ArrayList<Showroom>();
}

public boolean addVehicle(Showroom newVehicle) {
theVehicles.add(newVehicle);
return true;
}
}

.

import java.util.*;

public class ShowroomDriver {

public static void main(String[] args) {
Vehicle v1 = new Vehicle("renault", "clio", "12", "290890");
Showroom.addVehicle(v1);
}
}

基本上,我对如何将车辆对象添加到陈列室类中的数组列表感到困惑。如果有人能指出我正确的方向,我将不胜感激。

提前致谢。

最佳答案

您必须实例化 Showroom 类才能使用其属性和方法

theVehicles 的集合是 Vehicle 而不是 Showroom。

package cars;

import java.util.ArrayList;
import java.util.List;

public class Showroom {

private final List<Vehicle> theVehicles = new ArrayList<>();

public boolean addVehicle( Vehicle newVehicle ) {
theVehicles.add( newVehicle );
return true;
}

public static void main( String[] args ) {
final Showroom showroom = new Showroom();
final Vehicle v1 = new Vehicle( "renault", "clio", "12", "290890" );
showroom.addVehicle( v1 );
}
}

在 Vehicle 类中,'=' 运算符周围的错误,我想你想记住销售值(value)和客户姓名:

public void buyVehicle( String a, String b ) { // buy method for the vehicle
dateSold = a;
custName = b;
sold = true;
}

关于java - 将对象从另一个类添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743126/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com