gpt4 book ai didi

java - 如何根据状态打印列表项?

转载 作者:行者123 更新时间:2023-11-30 05:41:00 25 4
gpt4 key购买 nike

我正在创建一个电子拍卖系统,并且我有一种浏览拍卖的方法。每个拍卖都有一个状态(开放或关闭),我希望 browserAuctions 方法仅打印出已开放的拍卖。

我尝试了许多 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;

关于java - 如何根据状态打印列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com