2017-10-05 50 views
0

我還是很新的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>(); 

回答

0

確保,你已經宣佈Customer類所有的getter方法。因爲,我沒有宣佈。您需要遍歷ArrayList<Customer>

for(Customer custom : cust) 
{ 
    // call all your getter method from Customer class. 
    String customerName = custom.getName(); 
} 
+0

AirlineDriver是一個菜單驅動的程序。如果我在單獨的類中創建客戶,如何迭代ArrayList?我需要將Menu類移入AirlineDriver嗎? – miler4salem

+0

@ miler4salem你需要獲得填充列表來迭代 – Ravi