|
| 1 | +import java.io.IOException; |
| 2 | +import java.util.List; |
| 3 | +import java.util.Scanner; |
| 4 | +import javax.persistence.EntityManager; |
| 5 | +import javax.persistence.EntityManagerFactory; |
| 6 | +import javax.persistence.Persistence; |
| 7 | + |
| 8 | + |
| 9 | +public class MainMenu { |
| 10 | + private static Scanner input = new Scanner(System.in); |
| 11 | + private static EntityManagerFactory emf; |
| 12 | + private static EntityManager em; |
| 13 | + |
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + menu(); |
| 16 | + } |
| 17 | + |
| 18 | + //Create a menu with options |
| 19 | + public static void menu(){ |
| 20 | + emf = Persistence.createEntityManagerFactory("com.launchacademy.wishlist"); |
| 21 | + em = emf.createEntityManager(); |
| 22 | + String[] options = {". Add a new product", ". View wishlist", ". Exit"}; |
| 23 | + while(true){ |
| 24 | + for (int i = 0; i < options.length; i++){ |
| 25 | + System.out.println((i + 1) + options[i]); |
| 26 | + } |
| 27 | + System.out.println("CHOOSE a number HUMAN"); |
| 28 | + int choice = input.nextInt(); |
| 29 | + if( choice == options.length){ |
| 30 | + em.close(); |
| 31 | + emf.close(); |
| 32 | + System.exit(0); |
| 33 | + } |
| 34 | + else if (choice == 1){ |
| 35 | + addProduct(); |
| 36 | + } |
| 37 | + else if (choice == 2){ |
| 38 | + listWishes(); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + //Add a product |
| 44 | + private static void addProduct(){ |
| 45 | + try{ |
| 46 | + Product newProduct = new Product(); |
| 47 | + System.out.println("What product would you like to add?"); |
| 48 | + newProduct.setName(input.next()); |
| 49 | + System.out.println("What is the product's price?"); |
| 50 | + newProduct.setPrice(input.nextFloat()); |
| 51 | + System.out.println("What is the product's url?"); |
| 52 | + newProduct.setUrl(input.next()); |
| 53 | + em.getTransaction().begin(); |
| 54 | + em.persist(newProduct); |
| 55 | + em.getTransaction().commit(); |
| 56 | + } finally { |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + //List all products in wishlist |
| 61 | + private static void listWishes(){ |
| 62 | + List<Product> wishes = em.createQuery("SELECT p FROM Product p", Product.class).getResultList(); |
| 63 | + for (Product product : wishes){ |
| 64 | + System.out.println(product.getName() + " " + product.getPrice() + " " + product.getUrl()); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments