Guest User

Untitled

a guest
Mar 11th, 2020
299
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package E03_ShoppingSpree;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6.  
  7. public class Person {
  8. private String name;
  9. private double money;
  10. private List<Product> products;
  11.  
  12. public Person(String name, double money) {
  13. this.setName(name);
  14. this.setMoney(money);
  15. this.products = new ArrayList<>();
  16. }
  17.  
  18. public void buyProduct(Product product) {
  19. if (this.money < product.getCost()) {
  20. throw new IllegalArgumentException(this.name + " can't afford " + product.getName());
  21. }
  22. products.add(product);
  23. this.money -= product.getCost();
  24.  
  25. }
  26.  
  27. public String getName() {
  28. return name;
  29. }
  30.  
  31. private void setName(String name) {
  32. if (name == null || name.trim().isEmpty()) {
  33. throw new IllegalArgumentException("Name cannot be empty");
  34. }
  35. this.name = name.trim();
  36. }
  37.  
  38. private void setMoney(double money) {
  39. if (money < 0) {
  40. throw new IllegalArgumentException("Money cannot be negative");
  41. }
  42. this.money = money;
  43. }
  44.  
  45. @Override
  46. public String toString() {
  47. String postfix = this.products.size() > 0 ?
  48. products.stream()
  49. .map(Product::getName)
  50. .collect(Collectors.joining(", "))
  51. : "Nothing bought";
  52. return this.name + " - " + postfix;
  53. }
  54. }
RAW Paste Data