如何在java中创建一个对象位于驱动程序类中的对象?
问题描述:
我还是很新的Java,所以不要犹豫,如果你觉得我疯狂离开这里...如何在java中创建一个对象位于驱动程序类中的对象?
我有一个Java程序与多个对象蓝图类,菜单类和驱动程序类。驱动程序类调用菜单。在菜单类中,我创建了一个客户对象,同时只实例化了它的4个字段中的一个。该字段是唯一的ID字段。我想从位于驱动程序类中的ArrayList中获取其他3个字段。我如何从一个单独的类中的ArrayList中选择一个客户对象?
我尝试创建的第一个对象。
public class Customer {
private int id;
private String name;
private String address;
private String phone;
public static int count = 100;
public Customer(String name, String address, String phone) {
this.id = count;
this.name = name;
this.address = address;
this.phone = phone;
count++;
}
}
保留有客户
public class Reservation {
static Scanner scan = new Scanner(System.in);
private Customer customer;
private Flight flight;
private int partySize;
private double reservationCost;
final private double FIRST_CLASS_COST = 850.00;
final private double ECONOMY_COST = 450.00;
public Reservation(Customer customer, Flight flight, int partySize, double reservationCost) {
this.customer = customer;
this.flight = flight;
this.partySize = partySize;
this.reservationCost = reservationCost;
}
在驱动程序类,叫做AirlineDriver,有客户的ArrayList。在下面的代码中,如果我需要在驱动程序的ArrayList中获取其中一个Customers,那么如何创建一个Customer对象然后创建一个Reservation?
public class Menu {
static Scanner scan = new Scanner(System.in);
public Reservation createReservation() {
Customer cust = new Customer();
Flight flight;
Reservation reservation;
System.out.println("Are you a returning customer? (Y or N)");
String w = scan.nextLine();
while (!"Y".equals(w) || !"y".equals(w) || !"N".equals(w) || !"n".equals(w)) {
System.out.println("Incorrect key, please enter Y for Yes, and N for No.");
w = scan.nextLine();
}
if (w.equalsIgnoreCase("Y") || w.equalsIgnoreCase("y")) {
System.out.println("Welcome back and thank you for flying with us.");
System.out.println("What is your Customer ID?");
int custID = scan.nextInt();
}
如果客户已经存在,他们已经在这个ArrayList中。
public class AirlineDriver {
private static Scanner files;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Customer> cust = new ArrayList<Customer>();
答
确保,你已经宣布Customer
类所有的getter方法。因为,我没有宣布。您需要遍历ArrayList<Customer>
for(Customer custom : cust)
{
// call all your getter method from Customer class.
String customerName = custom.getName();
}
AirlineDriver是一个菜单驱动的程序。如果我在单独的类中创建客户,如何迭代ArrayList?我需要将Menu类移入AirlineDriver吗? – miler4salem
@ miler4salem你需要获得填充列表来迭代 – Ravi