[英]Adding objects to ArrayList from another class
我對編程非常陌生,目前正在嘗試編寫汽車展示廳應用程序。 我有一個車輛班,一個陳列室班,並且我正在嘗試使用陳列室駕駛員進行輸入。
我在將車輛對象添加到我的arraylist時遇到問題。 有人可以指出我正確的方向。
我的代碼:
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類才能使用其屬性和方法
車輛的集合是車輛而不是陳列室。
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類中,'='運算符周圍的一個錯誤,我想您想記住售出的價格和客戶名稱:
public void buyVehicle( String a, String b ) { // buy method for the vehicle
dateSold = a;
custName = b;
sold = true;
}
我認為這
private ArrayList <Showroom> theVehicles;
應該是這個
private ArrayList <Vehicle> theVehicles;
theVehicles = new ArrayList <Vehicle> ();
和這個
public boolean addVehicle( Showroom newVehicle )
應該
public boolean addVehicle( Vehicle newVehicle )
您不想要Vehicle
而不是ShowRoom
的ArrayList
嗎?
您的問題是您聲明了ShowRoom對象的ArrayList,但是想要的是Vehicle對象的ArrayList。
private ArrayList<Vehicle> theVehicles;
public boolean addVehicle(Vehicle v) {
theVehicles.add(v);
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.