rex897

public class Bag

Nov 4th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. import java.util.Iterator;
  2. import java.util.Random;
  3.  
  4. public class Bag extends Container {
  5.  
  6.     public Bag(String name, double weight, double capacity) {
  7.         super(name, weight, capacity);
  8.     }
  9.  
  10.     public Bag(String name, double weight, String properties, double capacity) {
  11.         super(name, weight, properties, capacity);
  12.     }
  13.  
  14.     @Override
  15.     public Item takeItem() throws ItemStoreException {
  16.         try {
  17.             Random rnd = new Random();
  18.             int takableItem = rnd.nextInt(content.size());
  19.             this.setCurrentWeight(this.getCurrentWeight() - content.get(takableItem).getWeight());
  20.             Item buffer = content.get(takableItem);
  21.             System.out.println("Предмет " + buffer.getName() + " удален из контейнера " + this.getName());
  22.             content.remove(takableItem);
  23.             return buffer;
  24.         } catch (NullPointerException e) {
  25.             e.getMessage();
  26.         }
  27.         throw new EmptyBagException();
  28.     }
  29.  
  30.     public Item found(String name) throws ItemStoreException {
  31.         Iterator<Item> iterator = content.iterator();
  32.         while (iterator.hasNext()) {
  33.             Item i = iterator.next();
  34.             if (i.getName().equals(name)) {
  35.                 System.out.println("Предмет " + name + " найден");
  36.                 return i;
  37.             }
  38.         }
  39.         System.out.println("Предмета " + name + " нет в мешке");
  40.         throw new NotFoundItemException();
  41.     }
  42.  
  43.     public static void main(String[] args) {
  44.         try {
  45.             Bag bag = new Bag("Сумка", 0.1, 10);
  46.             bag.put(new Item("предмет1", 4));
  47.             bag.put(new Item("предмет2", 1));
  48.             bag.printContainerInfo();
  49.             Item takeItem = bag.takeItem();
  50.             bag.printContainerInfo();
  51.             Item foundItem = bag.found("предмет2");
  52.         } catch (ItemStoreException e) {
  53.             e.getMessage();
  54.         }
  55.     }
  56. }
Add Comment
Please, Sign In to add comment