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);
? ? }
}
添加回答
舉報