簡體   English   中英

如何根據其狀態打印出列表項?

[英]How to print out a list item based on its status?

我正在創建一個電子拍賣系統,我有一種瀏覽拍賣的方法。 每個拍賣都有一個狀態(OPEN 或 CLOSED),我希望 browseAuctions 方法只打印已打開的拍賣。

我已經嘗試了許多 if 語句,它總是不斷地打印出每一次拍賣。

以下代碼是我為測試系統而硬編碼的一些內容

public List<Auction> auctionSystem() throws Exception {
    List<Auction> auctions = new LinkedList<Auction>();
    auctions.add(new Auction (35.50, 75.50, 40.00, users.get(3), LocalDateTime.now().minusSeconds(60), "Xbox", users.get(1), Status.OPEN));
    auctions.add(new Auction (27.00, 42.00, 32.00, users.get(2), LocalDateTime.now().plusSeconds(10), "PS3", users.get(1), Status.OPEN));
    auctions.add(new Auction (19.00, 21.00, 50.00, users.get(2), LocalDateTime.now().minusSeconds(1), "iPhone", users.get(1), Status.CLOSED));
    return auctions;
}

這是 Auction 類的構造函數:

public Auction (double startPrice, double reservePrice, double currentBid, User highestBidder, LocalDateTime closeDate, String item, User seller, Status status) throws Exception {
    if (closeDate.isBefore(LocalDateTime.now().plusDays(7))) {
        this.startPrice = startPrice;
        this.reservePrice = reservePrice;
        this.closeDate = closeDate;
        this.item = item;
        this.highestBidder = highestBidder;
        this.currentBid = currentBid;
        this.seller = seller;
        UP = currentBid * 0.20;
        LOW = currentBid * 0.10;
    } else {
        throw new Exception ("CloseDate error: " + closeDate.format(formatter));
    }
}

這是Status類:

public enum Status {
    OPEN, CLOSED
}

這是Auction類中瀏覽拍賣的方法:

public void browseAuctions () {

    System.out.println("-----All Auctions-----");

    for (Auction a : auctions) {
        if (a.status.equals(Status.OPEN)){  
            System.out.println("Item: " + a.getItem());
            System.out.println("Current Bid: " + "£" + a.getCurrentBid());
            System.out.println("Close Date: " + a.getCloseDate());
            }
        }
    }
}

status在構造函數中被忽略,因此所有Auction實例都不會根據循環中的條件進行限定。 我想知道所有通過,唯一的解釋是Status.OPEN是默認設置的,這意味着您在代碼中有以下聲明:

private Status status = Status.OPEN;

由於它在構造函數中缺失,它沒有設置為新的傳遞值。 這些是可變字段的問題,因此我建議您將它們聲明為final並使用輔助構造函數解析默認值:

private final Status status;
// the rest

public Auction (double sPrice, double rPrice, double currentBid, 
                User highestBidder, LocalDateTime closeDate, String item, User seller) 
{
    this(sPrice, rPrice, currentBid, highestBidder, closeDate, item, seller, Status.OPEN)
}

無論如何,要解決您的問題,請使用以下命令完成構造函數:

this.status = status;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM