kristina7

НП - Лаб 3-1 Пицерија

Nov 19th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.85 KB | None | 0 0
  1. /*
  2. Треба да се развие систем за електронска нарачка од пицерија. Менито на пицеријата се состои од следново:
  3.  
  4. Pizza:
  5.  
  6. Standard: 10$
  7. Pepperoni: 12$
  8. Vegetarian: 8$
  9. Extra
  10.  
  11. Ketchup 3$
  12. Coke 5$
  13. За да го претставите менито, секоја ставка треба да имплементира interface Item која опишува една ставка од менито и ги дефинира следниве методи:
  14.  
  15. getPrice():int - ја дава цената за конкретната ставка
  16. Следно, дефинирајте две класи ExtraItem и PizzaItem за да може да правите разлика меѓу пици и останатите работи во нарачката. И двете класи треба да имаат еден конструктор кој прима еден String аргумент.
  17.  
  18. ExtraItem(String type) - валидни вредности за type се { "Coke", "Ketchup" }
  19. PizzaItem(String type) - валидни вредности за type се { Standard , Pepperoni , Vegetarian }
  20. Ако за type се проследи некоја невалидна вредност (која ја нема на менито) треба да се фрли исклучок InvalidExtraTypeException, односно InvalidPizzaTypeException.
  21.  
  22. Последно имплементирајте ја класата Order. Таа треба да ги нуди следните функционалности:
  23.  
  24. Order() - креира нова празна нарачка
  25. addItem(Item item, int count) - соодветната ставка се додава во нарачката (count означува колку примероци сакаме од дадената ставка). Aко count е поголем од 10 се фрла исклучок ItemOutOfStockException(item). Доколку во нарачката веќе ја има соодветната ставка Item тогаш истата се заменува со нова. Следниот код резултира со нарачка со една стандардна пица:
  26.  
  27. Order order = new Order(); order.addItem(new PizzaItem("Standard"), 2); order.addItem(new PizzaItem("Standard"), 1);
  28.  
  29. getPrice():int - ја враќа вкупната цена на нарачката
  30.  
  31. displayOrder() - ја печати содржината на нарачката со соодветни редни броеви пред секоја ставка, името, количината и збирна сума на ставката, како и вкупна сума за целата нарачка. За редниот број се резервирани 3 места порамнети во десно, за имињата на ставките се резервирани 15 места со порамнување од лево, за кардиналноста две места порамнети во десно и за цената на една ставка 5 места порамнети во десно. За "Total:" се резервирани 22 места со порамнување од лево и за вкупната цена 5 места порамнети во десно. Пример:
  32.   1.Standard       x 2   20$
  33.   2.Vegetarian     x 1    8$
  34.   3.Coke           x 3   15$
  35. Total:                   43$
  36. Редоследот по кој се печатат ставките е оној по кој тие се внесувани во нарачката. Доколку некоја ставка се внесе повторно нејзиното место не се менува.
  37.  
  38. removeItem(int idx) - се отстранува нарачката со даден индекс (сите нарачки со поголеми индекси се поместуваат во лево). Доколку не постои нарачка со таков индекс треба да се фрли исклучок ArrayIndexOutOfBоundsException(idx)
  39. lock() - ја заклучува нарачката. За да може нарачката да се заклучи треба истата да има барем една ставка, во спротивно фрлете исклучок EmptyOrderException.
  40. Откако ќе се заклучи нарачката треба веќе да не може да се менува со методите removeItem, addItem. Повикот на овие методи резултира со исклучок од типот OrderLockedException.
  41. */
  42. import java.util.*;
  43.  
  44. class Order{
  45.     List<Item> items;
  46.     List<Integer> kolicini;
  47.     boolean locked;
  48.     public Order() {
  49.         items = new ArrayList<>();
  50.         kolicini = new ArrayList<>();
  51.         locked = false;
  52.     }
  53.     public void addItem(Item item, int count) throws ItemOutOfStockException, OrderLockedException {
  54.         if(locked)
  55.             throw new OrderLockedException();
  56.         if(count > 10)
  57.             throw new ItemOutOfStockException(item.toString());
  58.         int idx = findIndex(item);
  59.         if(idx == -1) {
  60.             items.add(item);
  61.             kolicini.add(count);
  62.         }else {
  63.             kolicini.set(idx, count);
  64.         }
  65.     }
  66.     public int findIndex(Item i) {
  67.         int idx = -1;
  68.         for (Item item : items) {
  69.             if(item.toString().equals(i.toString()))
  70.                 idx = items.indexOf(item);     
  71.         }
  72.         return idx;
  73.     }
  74.     public int getPrice() {
  75.         int suma = 0;
  76.         for (Item item : items) {
  77.             suma += item.getPrice() * kolicini.get(items.indexOf(item));
  78.         }
  79.         return suma;
  80.     }
  81.     public void displayOrder() {
  82.         for (Item item : items) {
  83.             String s="";
  84.             int i = items.indexOf(item);
  85.             int kolicina = kolicini.get(i);
  86.             int total = kolicina * item.getPrice();
  87.             String name = item.toString();
  88.             s = String.format("%3d.%-15sx%2d%5d$", i+1, name, kolicina, total);
  89.             System.out.println(s);
  90.         }
  91.         System.out.println(String.format("%-22s%5d$", "Total:", getPrice()));
  92.     }
  93.     public void removeItem(int idx) throws ArrayIndexOutOfBoundsException, OrderLockedException {
  94.         if(locked)
  95.             throw new OrderLockedException();
  96.         if(idx < 0 || idx >= items.size())
  97.             throw new ArrayIndexOutOfBoundsException(idx);
  98.          items.remove(idx);
  99.     }
  100.     public void lock() throws EmptyOrder {
  101.         if(items.size() == 0)
  102.             throw new EmptyOrder();
  103.         locked = true;
  104.     }
  105. }
  106.  
  107. interface Item{
  108.     public int getPrice();
  109. }
  110.  
  111. class PizzaItem implements Item{
  112.     String type;
  113.     public PizzaItem(String type) throws InvalidPizzaTypeException {
  114.         if(type.equals("Standard") || type.equals("Pepperoni") || type.equals("Vegetarian"))
  115.             this.type = type;
  116.         else
  117.             throw new InvalidPizzaTypeException();
  118.     }
  119.    
  120.     @Override
  121.     public int getPrice() {
  122.         if(type.equals("Standard"))
  123.             return 10;
  124.         if(type.equals("Vegetarian"))
  125.             return 8;
  126.         return 12;
  127.     }
  128.     @Override
  129.     public String toString() {
  130.         return type;
  131.     }
  132. }
  133. class ExtraItem implements Item{
  134.     String type;
  135.     public ExtraItem(String type) throws InvalidExtraTypeException {
  136.         if(type.equals("Coke") || type.equals("Ketchup"))
  137.             this.type = type;
  138.         else
  139.             throw new InvalidExtraTypeException();
  140.     }
  141.     @Override
  142.     public int getPrice() {
  143.         if(type.equals("Coke"))
  144.             return 5;
  145.         return 3;
  146.     }
  147.     @Override
  148.     public String toString() {
  149.         return type;
  150.     }
  151. }
  152. class InvalidPizzaTypeException extends Exception{
  153.     public InvalidPizzaTypeException() {
  154.         super("Invalid pizza type");
  155.     }
  156. }
  157. class InvalidExtraTypeException extends Exception{
  158.     public InvalidExtraTypeException() {
  159.         super("Invalid extra type");
  160.     }
  161. }
  162. class ItemOutOfStockException extends Exception{
  163.     public ItemOutOfStockException(String item) {
  164.         super(item);
  165.     }
  166. }
  167. class ArrayIndexOutOfBoundsException extends Exception{
  168.     public ArrayIndexOutOfBoundsException(int idx) {
  169.         super(idx + "");
  170.     }
  171. }
  172. class EmptyOrder extends Exception{
  173.     public EmptyOrder() {
  174.         super("Empty Order");
  175.     }
  176. }
  177. class OrderLockedException extends Exception {
  178.     public OrderLockedException() {
  179.         super("Order locked");
  180.     }
  181. }
  182.  
  183. public class PizzaOrderTest {
  184.  
  185.     public static void main(String[] args) {
  186.         Scanner jin = new Scanner(System.in);
  187.         int k = jin.nextInt();
  188.         if (k == 0) { //test Item
  189.             try {
  190.                 String type = jin.next();
  191.                 String name = jin.next();
  192.                 Item item = null;
  193.                 if (type.equals("Pizza")) item = new PizzaItem(name);
  194.                 else item = new ExtraItem(name);
  195.                 System.out.println(item.getPrice());
  196.             } catch (Exception e) {
  197.                 System.out.println(e.getClass().getSimpleName());
  198.             }
  199.         }
  200.         if (k == 1) { // test simple order
  201.             Order order = new Order();
  202.             while (true) {
  203.                 try {
  204.                     String type = jin.next();
  205.                     String name = jin.next();
  206.                     Item item = null;
  207.                     if (type.equals("Pizza")) item = new PizzaItem(name);
  208.                     else item = new ExtraItem(name);
  209.                     if (!jin.hasNextInt()) break;
  210.                     order.addItem(item, jin.nextInt());
  211.                 } catch (Exception e) {
  212.                     System.out.println(e.getClass().getSimpleName());
  213.                 }
  214.             }
  215.             jin.next();
  216.             System.out.println(order.getPrice());
  217.             order.displayOrder();
  218.             while (true) {
  219.                 try {
  220.                     String type = jin.next();
  221.                     String name = jin.next();
  222.                     Item item = null;
  223.                     if (type.equals("Pizza")) item = new PizzaItem(name);
  224.                     else item = new ExtraItem(name);
  225.                     if (!jin.hasNextInt()) break;
  226.                     order.addItem(item, jin.nextInt());
  227.                 } catch (Exception e) {
  228.                     System.out.println(e.getClass().getSimpleName());
  229.                 }
  230.             }
  231.             System.out.println(order.getPrice());
  232.             order.displayOrder();
  233.         }
  234.         if (k == 2) { // test order with removing
  235.             Order order = new Order();
  236.             while (true) {
  237.                 try {
  238.                     String type = jin.next();
  239.                     String name = jin.next();
  240.                     Item item = null;
  241.                     if (type.equals("Pizza")) item = new PizzaItem(name);
  242.                     else item = new ExtraItem(name);
  243.                     if (!jin.hasNextInt()) break;
  244.                     order.addItem(item, jin.nextInt());
  245.                 } catch (Exception e) {
  246.                     System.out.println(e.getClass().getSimpleName());
  247.                 }
  248.             }
  249.             jin.next();
  250.             System.out.println(order.getPrice());
  251.             order.displayOrder();
  252.             while (jin.hasNextInt()) {
  253.                 try {
  254.                     int idx = jin.nextInt();
  255.                     order.removeItem(idx);
  256.                 } catch (Exception e) {
  257.                     System.out.println(e.getClass().getSimpleName());
  258.                 }
  259.             }
  260.             System.out.println(order.getPrice());
  261.             order.displayOrder();
  262.         }
  263.         if (k == 3) { //test locking & exceptions
  264.             Order order = new Order();
  265.             try {
  266.                 order.lock();
  267.             } catch (Exception e) {
  268.                 System.out.println(e.getClass().getSimpleName());
  269.             }
  270.             try {
  271.                 order.addItem(new ExtraItem("Coke"), 1);
  272.             } catch (Exception e) {
  273.                 System.out.println(e.getClass().getSimpleName());
  274.             }
  275.             try {
  276.                 order.lock();
  277.             } catch (Exception e) {
  278.                 System.out.println(e.getClass().getSimpleName());
  279.             }
  280.             try {
  281.                 order.removeItem(0);
  282.             } catch (Exception e) {
  283.                 System.out.println(e.getClass().getSimpleName());
  284.             }
  285.         }
  286.     }
  287.  
  288. }
Add Comment
Please, Sign In to add comment