我正在创建一个电子拍卖系统,并且有一种浏览拍卖的方法。每个拍卖都有一个状态(“已打开”或“已关闭”),我希望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;

08-06 20:44