2016-03-03 52 views
0

我想創建一個方法來列出一個ArrayList中的元素,但該方法只返回最新的對象的值:對象的一個​​ArrayList列出參數

對象:

//Constructor for guests at the hotel 
public Guest (String name, String checkinDate, String checkoutDate, double depAmt) 
{ 
    gstName = name; 
    checkIn = checkinDate; 
    checkOut = checkoutDate; 
    deposit = depAmt; 
} 

ArrayList中當前對象:

//Fills the roster with three guests to start the program 
public static void fillGuest() 
{ 
    Guest guest1 = new Guest("Mike P.", "2/13/16", "2/23/16", 360.00); 
    guestList.add(guest1); 
    Guest guest2 = new Guest("Randall M.", "4/10/16", "4/17/16", 120.00); 
    guestList.add(guest2); 
    Guest guest3 = new Guest("Bo-Diddly.", "4/20/16", "4/23/16", 600.00); 
    guestList.add(guest3); 
} 

方法列出ArrayList中的對象:

public static void returnGuests() 
{ 
    System.out.println("Currently checked in " + guestList.size() + " guests:"); 
    for (int i = 0; i <= guestList.size() - 1; i++) 
    { 
     System.out.println(guestList.get(i)); 
    } 
} 

輸出:

Currently checked in 3 guests: 
Bo-Diddly. 4/20/16 4/23/16 600.0 
Bo-Diddly. 4/20/16 4/23/16 600.0 
Bo-Diddly. 4/20/16 4/23/16 600.0 

Enter command: 

如何顯示每個客戶對象的單個對象的參數?

+10

你肯定還沒有定義的字段,靜態的?我們展示完整的客戶代碼源 –

+0

你看着使用'foreach'循環呢?這將代替你現有的for循環。 – Brian

+3

這是一個非常強烈的跡象表明你的'客人'類寫錯了。 –

回答

0

Guest對象應該如下。請注意,字段中缺少static修飾符。另請注意,使用this關鍵字。如果您使用的是帶有static變量,那麼你的IDE應該給你一個警告,它會被解釋爲MyClass.var,而不是this.var

您的問題是,當您創建新的Guest對象時,所有Guest對象將具有最後一組變量。您需要使用「實例」變量而不是「類」變量。

如果您想了解更多關於靜態「類」變量的話題,請參閱Understanding Class Members

public class Guest { 

    String gstName, checkIn, checkOut; 
    double deposit; 

    public Guest (String name, String checkinDate, String checkoutDate, double depAmt) 
    { 
     this.gstName = name; 
     this.checkIn = checkinDate; 
     this.checkOut = checkoutDate; 
     this.deposit = depAmt; 
    } 
} 
相關問題