Advertisement
Guest User

Person

a guest
Feb 25th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. package shoppingSpree;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import java.util.stream.Collectors;
  7.  
  8. public class Person {
  9.  
  10.     private String name;
  11.     private int money;
  12.     private List<Product> products;
  13.  
  14.     public Person(String name, int money) {
  15.         this.setName(name);
  16.         this.setMoney(money);
  17.         this.products = new ArrayList<>();
  18.     }
  19.  
  20.     public void tryPurchase(Product product) {
  21.         if (this.getMoney() >= product.getCost()) {
  22.             this.setMoney(this.getMoney() - product.getCost());
  23.             this.addProduct(product);
  24.         } else {
  25.             throw new IllegalStateException(String.format("%s can't afford %s", this.getName(), product.getName()));
  26.         }
  27.     }
  28.  
  29.     @Override
  30.     public String toString() {
  31.         if (this.getProducts().size() == 0) {
  32.             return this.getName() + " - Nothing bought";
  33.         }
  34.         return this.getName() + " - " + String.join(", ", this.getProducts().stream().map(Object::toString).collect(Collectors.toList()));
  35.     }
  36.  
  37.     private void addProduct(Product product) {
  38.         this.products.add(product);
  39.     }
  40.  
  41.     private String getName() {
  42.         return name;
  43.     }
  44.  
  45.     private int getMoney() {
  46.         return money;
  47.     }
  48.  
  49.     public List<Product> getProducts() {
  50.         return Collections.unmodifiableList(this.products);
  51.     }
  52.  
  53.     private void setName(String name) {
  54.         if (name == null || name.trim().length() == 0) {
  55.             throw new IllegalArgumentException("Name cannot be empty");
  56.         }
  57.         this.name = name;
  58.     }
  59.  
  60.     private void setMoney(int money) {
  61.         if (money < 0) {
  62.             throw new IllegalArgumentException("Money cannot be negative");
  63.         }
  64.         this.money = money;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement