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