1 回答
TA贡献1846条经验 获得超7个赞
以下情况看起来不正确:
for(Person p:bidders) {
// bidders holds Person objects and you are checking for boolean. p.getName() == nameOfBidder will evaluate to true. Perhaps you want to check for name equality first and then contains.
if (bidders.contains(p.getName()==nameOfBidder)) {
}
}
for (Item i:allItems ) {
// allItems holds Item objects and you are checking by name string
if(!(allItems.contains(i.getName()))){
}
}
此外,可以简化初始空值和检查条件。
给你,大大简化的代码:
public void addBid(String itemName, String nameOfBidder, double price) {
if (itemName == null || nameOfBidder == null) {
throw new NullPointerException("Name of the bidder cannot be null");
}
if (itemName.equals("") || nameOfBidder.equals("") || price <= 0) {
throw new IllegalArgumentException("Name of the bidder cannot be empty");
}
Optional<Person> person = bidders.stream().filter(e -> e.getName().equals(nameOfBidder)).findAny();
Optional<Item> item = items.stream().filter(e -> e.getName().equals(itemName)).findAny();
if (person.isPresent()) {
checkItemAndAddBid(item, person.get(), price);
} else {
Person newPerson = new Person(nameOfBidder);
bidders.add(newPerson);
System.out.println("Creating a new bidder: "+newPerson.getName());
checkItemAndAddBid(item, newPerson, price);
}
}
public void checkItemAndAddBid(Optional<Item> item, Person person, double price) {
if (!item.isPresent()) {
throw new NoSuchElementException("There is no such Item in the Auction");
} else {
item.get().addBid(person, price);
}
}
添加回答
举报