Advertisement
SageTheWizard

pawnShop.java

Apr 1st, 2018
476
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.89 KB | None | 0 0
  1. /*
  2.   Author: Jacob Gallucci
  3.   Course: CMPSC 221
  4.   Assignment: Programming Assignment 3 - Store Shopping Cart  - Main
  5.   Due date: 4/2/2018
  6.   File: pawnShop.java
  7.   Purpose: Driver for Item.java .. Allows user to add items to their cart, remove items from their cart and check out
  8.   Compiler/IDE: OpenJDK 1.8.0_151 (compiled from CLI) - Atom / Vim text editors
  9.   Operating system: Debian Stretch 9
  10.   Reference(s):
  11.                   https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html - Arraylist documentation
  12.                   https://www.geeksforgeeks.org/arraylist-in-java/ - Arraylist examples (used to get the proper format and such)
  13. */
  14. import java.io.*;
  15. import java.util.*;
  16. import java.text.NumberFormat;
  17.  
  18. public class pawnShop
  19. {
  20.   public static void main(String[] args) // Main
  21.   {
  22.     ArrayList<Item> shopStock = new ArrayList<Item>(15); // Shop stock, contains 15 items (object)
  23.     ArrayList<Item> cart = new ArrayList<Item>(); // User cart, Note: Initialized Here
  24.     Scanner keyboard = new Scanner(System.in); // keyboard scanner - user input
  25.     int input; // Integer for input
  26.     int itemChoice;  // Item choice when adding items to cart / deleting items from cart
  27.     int quan;  // Quantity to add to cart / remove from cart
  28.     boolean cartExists = false;  // If the cart is not created, this is false and you cannot add stuff to a cart
  29.  
  30.     for (int i = 1; i <= 15; i++) // initializes the shop's stock
  31.       shopStock.add(new Item());
  32.  
  33.     setupStock(shopStock); // Adds items from .txt file to the stock
  34.  
  35.     System.out.println("Welcome to Ants in My Eyes Johnson's InterGalactic Pawn Shop!\n");
  36.  
  37.     do // Main do loop
  38.     {
  39.       displayMenu(); // displays main menu
  40.       do // user input loop, loops while the user selection is not in range of the menu options
  41.       {
  42.         input = getInput(keyboard); // gets input from user
  43.         if ((input < 1) || (input > 4)) // if the input is outside of the range of the menu
  44.           System.out.println("Please Input a number from above!");
  45.       }while((input < 1) || (input > 4));
  46.  
  47.       if (input == 1) // creates cart
  48.       {
  49.         cartExists = true;
  50.         System.out.println("Cart Created!");
  51.       }
  52.       else if ((input == 2) && cartExists) // Adds item to cart (if cart exists)
  53.       {
  54.         do // Loops while out of range of menu (1-3)
  55.         {
  56.           displayInvCategories(); // Displays categories of items
  57.           input = getInput(keyboard); // gets input of which category the individual wants to purchase from
  58.           if ((input < 1) || (input > 3))  // if input is out of range (1-3)
  59.             System.out.println("Please Input a number from above!");
  60.         }while((input < 1) || (input > 3));
  61.  
  62.         displayItems(input, shopStock); // Displays items of the selected category
  63.         System.out.print("Enter the product number of your desired item: ");
  64.         itemChoice = getInput(keyboard); // gets user's desired item by product code
  65.  
  66.         if (validItem(itemChoice, shopStock)) // If the item is valid
  67.         {
  68.           if (getQuantity(itemChoice, shopStock) > 0) // If the item is in stock
  69.           {
  70.             quan = getQuantity(itemChoice, shopStock); // stores # of items in stock
  71.             System.out.print("Enter quantity of item (Max: " + quan + "): ");
  72.  
  73.             do // Loops while user's quantity is less than 0 or greater than # of items in stock
  74.             {
  75.               input = getInput(keyboard); // gets user's desired quantity
  76.               if (input > quan)
  77.                 System.out.println("Invalid amount!  We don't have enough in stock!");
  78.                     else if (input < 0)
  79.                         System.out.println("You can't magically add stuff to the stock by purchasing negative amounts!");
  80.             }while (input > quan || input < 0);
  81.  
  82.             addItemToCart(input, itemChoice, cart, shopStock); // adds item to cart
  83.             System.out.println("Item successfully Added to your cart!\n");
  84.  
  85.             displayCart(cart); // displays updated cart
  86.           }
  87.           else // if item quantity = 0
  88.             System.out.println("Item is temporarily out of stock!");
  89.         }
  90.         else // if the item inputted does not exist ... NOTE: Does not check if the item entered is in the category  currently viewed it's a FEATURE
  91.           System.out.println("Invalid Product Code!");
  92.       }
  93.       else if ((input == 3) && cartExists && !cart.isEmpty()) // Deletes item from cart
  94.       {
  95.         displayCart(cart); // displays cart
  96.         System.out.print("Enter the item number of the product you wish to remove from the cart: ");
  97.         itemChoice = getInput(keyboard); // gets user input for item they wish to remove
  98.  
  99.         if (validItem(itemChoice, cart)) // if the item is valid
  100.         {
  101.           quan = getQuantity(itemChoice, cart); // gets quantity of item in cart
  102.           System.out.print("Enter the quantity you wish to remove from the cart (Max: " + quan + "): ");
  103.  
  104.           do // loops while input is out of range of quantity in the cart
  105.           {
  106.             input = getInput(keyboard);
  107.             if ((input > quan) || (input < 0))
  108.               System.out.println("Invalid amount! Enter a valid quantity: ");
  109.           }while ((input > quan) || (input < 0));
  110.  
  111.           removeFromCart(input, itemChoice, cart, shopStock); // removes item from cart
  112.           System.out.println("Successfully removed item from cart!");
  113.         }
  114.         else // if the item is not in the cart
  115.           System.out.println("Item does not exist in your cart!");
  116.       }
  117.       else if ((input == 4) && cartExists && !(cart.isEmpty())) // if the user wishes to check out
  118.       {
  119.         checkout(cart, keyboard); // calls checkout method
  120.       }
  121.       else if ((input == 4) && (cart.isEmpty()) && cartExists) // if the user wants to check out but their cart is empty
  122.       {
  123.         System.out.println("Your cart is empty!!! Buy something!");
  124.         input = -1;
  125.       }
  126.       else if ((input != 1) && !cartExists) // if the user wants to do ANYTHING and the cart doesn't exist
  127.       {
  128.         System.out.println("Cart Doesn't Exist! Type '1' to create one!");
  129.         input = -1;
  130.       }
  131.  
  132.     }while(input != 4);
  133.  
  134.     System.exit(0); // ends program
  135.  
  136.   }
  137. ///////////////////////////////////////////////METHODS///////////////////////////////////////////////////////////
  138.  
  139.   private static void checkout(ArrayList<Item> userCart, Scanner keys) // Checkout method
  140.   {
  141.     double cost = 0.0; // cost of cart
  142.     String name = ""; // Card holder name
  143.     String cardType = ""; // Card type
  144.     String expirationDate = ""; // expiration date of the card
  145.     String cardNum = ""; // credit card number
  146.     boolean validExpire = false; // used to determine if the expiration date of the card is a valid date
  147.     boolean validCard = false;  // used to determine if the Credit card is 16 integers in length
  148.     Locale locale = new Locale("en", "US"); // sets currency locale to USA
  149.     NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(locale); // sets number format to USA
  150.  
  151.     displayCart(userCart); // Displays cart
  152.     System.out.println("These are the items you are purchasing...");
  153.  
  154.     for (int i = 0; i < userCart.size(); i++) // Sums the price of the the cart
  155.       cost = cost + userCart.get(i).getPrice() * userCart.get(i).getQuantity();
  156.     cost = cost * 1.10; // adds tax
  157.  
  158.     System.out.println("Total Cost + Intergalactic Federation Tax (10%): " + moneyFormat.format(cost) + "\n");
  159.     System.out.print("Enter Card Holder Name: ");
  160.     name = keys.nextLine(); // gets user's name
  161.  
  162.     do // Loops while card type is invalid
  163.     {
  164.       System.out.print("Enter Card Type (Visa / Mastercard / InterStellar): ");
  165.       cardType = keys.nextLine(); // gets card type
  166.  
  167.       if (!(cardType.equalsIgnoreCase("VISA")) && !(cardType.equalsIgnoreCase("MASTERCARD")) && !(cardType.equalsIgnoreCase("INTERSTELLAR")))
  168.         System.out.println("Invalid Card Type!");
  169.     }while(!(cardType.equalsIgnoreCase("VISA")) && !(cardType.equalsIgnoreCase("MASTERCARD")) && !(cardType.equalsIgnoreCase("INTERSTELLAR")));
  170.  
  171.     do // loops while the inputted format of the expiration date is invalid
  172.     {
  173.       System.out.print("Enter card expiration date (MM/YY): ");
  174.       expirationDate = keys.nextLine(); // gets expiration date from the user
  175.       validExpire = checkExp(expirationDate); // checks id expiration date is valid
  176.  
  177.       if (!validExpire) // if the expiration date is invalid
  178.         System.out.println("Invalid expiration date!");
  179.  
  180.     }while (!validExpire);
  181.  
  182.     do // Loops while the credit card number is not  valid
  183.     {
  184.       System.out.print("Input your 16 digit card number: ");
  185.       cardNum = keys.nextLine();  // gets user card number
  186.       if (!cardIsInt(cardNum) || cardNum.length() != 16) // checks if the card number is all integers and if the card number length is not 16
  187.       {
  188.         validCard = false;
  189.         System.out.println("Invalid Card Number!");
  190.       }
  191.       else
  192.         validCard = true;
  193.  
  194.     }while(!validCard);
  195.  
  196.     System.out.println("\nProcessing your order...\n");
  197.     // Outputs billing information
  198.     System.out.println("Card Holder: " + name);
  199.     System.out.println("Card Type: " + cardType);
  200.     System.out.println("Card Number: " + cardNum);
  201.     System.out.println("Card Expiration Date: " + expirationDate);
  202.     System.out.println("_______________________________________________");
  203.     System.out.println("Total Charged: " + moneyFormat.format(cost));
  204.     System.out.println("\n\nThank you for stopping by at Ants in my Eyes Johnson's Intergalactic Pawn shop! Please come again and spend more money!");
  205.  
  206.     return;
  207.   }
  208.  
  209.   private static boolean cardIsInt(String card) // determines if card number consists of integers
  210.   {
  211.     for (int i = 0; i < card.length(); i++) // Loops through card number string
  212.     {
  213.       if (!Character.isDigit(card.charAt(i))) // if the character at i in the card number string isn't a digit returns FALSE
  214.         return false;
  215.     }
  216.     return true; // returns true if passes all tests
  217.   }
  218.  
  219.   private static boolean checkExp(String userExp) // Checks if expiration date is valid
  220.   {
  221.     int monthTens = 0;
  222.     int monthOnes = 0;
  223.  
  224.     if (userExp.length() != 5) // checks if expiration date is a valid length (5)
  225.       return false;
  226.     else if (userExp.charAt(2) != '/') // checks if the middle character is a '/'
  227.       return false;
  228.  
  229.     // checks if every non '/' character is a digit
  230.     if (!Character.isDigit(userExp.charAt(0)) || !Character.isDigit(userExp.charAt(1)) || !Character.isDigit(userExp.charAt(3)) || !Character.isDigit(userExp.charAt(4)))
  231.       return false;
  232.  
  233.     monthTens = Character.getNumericValue(userExp.charAt(0)); // gets month tens digit
  234.     monthOnes = Character.getNumericValue(userExp.charAt(1)); // gets month ones digit
  235.  
  236.     if ((((monthTens * 10) + monthOnes) > 12) || ((monthTens * 10) + monthOnes) < 1 ) // if month digit is greater 12 or less than 1
  237.       return false;
  238.  
  239.     return true; // if passes all tests, returns true
  240.  
  241.   }
  242.  
  243.   private static void removeFromCart(int quantityToRemove, int itemToRemove, ArrayList<Item> userCart, ArrayList<Item> stock) // remove from cart function
  244.   {
  245.     int i = 0; // i and j are incrementers used in do loop
  246.     int j = 0;
  247.     boolean backToStock = false;
  248.     boolean removedFromCart = false;
  249.     do // Loops while it's not removed from cart (don't worry, we've already checked if the item is valid!)
  250.     {
  251.       if (!(userCart.isEmpty()) && (itemToRemove == userCart.get(i).getNum())) // if the cart's not empty and item current item (i) is the item to remove
  252.       {
  253.         userCart.get(i).setQuantity(userCart.get(i).getQuantity() - quantityToRemove); // cart's item quantity is removed by the amount the user whishes to remove
  254.         if (userCart.get(i).getQuantity() == 0) // if quantity = 0, just remove the object from the cart array list
  255.           userCart.remove(i);
  256.         do // loops while item is not back in stock
  257.         {
  258.           if (itemToRemove == stock.get(j).getNum()) // if the item to remove is the same as the current item in the stock (j)
  259.           {
  260.             stock.get(j).setQuantity(stock.get(j).getQuantity() + quantityToRemove); // adds quantity back to the stock
  261.             backToStock = true; // adds item back into stock
  262.           }
  263.           j++;
  264.         }while(!backToStock);
  265.         removedFromCart = true; // removed from cart is set to true
  266.       }
  267.       i++;
  268.     }while(!removedFromCart);
  269.   }
  270.  
  271.   private static void displayCart(ArrayList<Item> userCart) // display cart
  272.   {
  273.     for (int i = 0; i < userCart.size(); i++) // loops through whole cart and displays each item
  274.     {
  275.       System.out.println(userCart.get(i));
  276.       System.out.println("\n");
  277.     }
  278.  
  279.   }
  280.  
  281.   private static void addItemToCart(int amount, int itemToAdd, ArrayList<Item> userCart, ArrayList<Item> stock) // adds item to cart
  282.   {
  283.     int i = 0;
  284.     int j = 0;
  285.     boolean inCart = false;
  286.     do // Loops while item has not been added to the cart and i is less than stock size
  287.     {
  288.       if (itemToAdd == stock.get(i).getNum()) // if current item is the stock is the item to add (i)
  289.       {
  290.         stock.get(i).setQuantity(stock.get(i).getQuantity() - amount); // removes the amount to add to the cart from the stock
  291.         if (!(userCart.isEmpty())) // if the cart is not empty
  292.         {
  293.           do // Loops through cart to check if the item is already in it
  294.           {
  295.             if (itemToAdd == userCart.get(j).getNum()) // if item is already in cart
  296.               inCart = true;
  297.             else
  298.               j++;
  299.           }while((!inCart) && (j < userCart.size()));
  300.         }
  301.         if (!inCart || userCart.isEmpty()) // if the item is not in the cart, add a new item to the cart
  302.           userCart.add(new Item(itemToAdd, amount, stock.get(i).getName(), stock.get(i).getCatagory(), stock.get(i).getPrice()));
  303.         else // if it's  already int he cart just increase the quantity
  304.           userCart.get(j).setQuantity(userCart.get(j).getQuantity() + amount);
  305.       }
  306.       i++;
  307.     }while((!inCart) && (i < stock.size()));
  308.   }
  309.  
  310.   private static int getQuantity(int choice, ArrayList<Item> stock) // get quantity of item method
  311.   {
  312.     int i = 0;
  313.     int quantityOfItem = -1;
  314.     do // Loops through stock /cart to get the quantity of the item in the respective thing
  315.     {
  316.       if (choice == stock.get(i).getNum()) // if item is found
  317.         quantityOfItem = stock.get(i).getQuantity(); // stores the quantity in quantityOfItem
  318.       i++;
  319.     }while((quantityOfItem == -1) && i < stock.size());
  320.     return quantityOfItem; // returns quantity of the item in cart / stock
  321.   }
  322.  
  323.   private static boolean validItem(int choice, ArrayList<Item> stock) // determines if the item is a valid item
  324.   {
  325.     boolean inStock = false;
  326.     for (int i = 0; i < stock.size(); i++) // loops through all items in the stock/cart to see if the item is in the stock / cart
  327.     {
  328.       if (choice == stock.get(i).getNum()) // if item is found
  329.         inStock = true;
  330.     }
  331.  
  332.     return inStock; // returns whether or not the item is in the cart
  333.   }
  334.  
  335.   private static void displayItems(int cata, ArrayList<Item> stock) // displays the items of their respective categories
  336.   {
  337.     System.out.println("\n");
  338.     if (cata == 1) // if user chooses category "1"
  339.     {
  340.       for (int i = 0; i < stock.size(); i++) // loops through stock looking for item of category "SHIP UPGRADES"
  341.       {
  342.         if ((stock.get(i).getCatagory()).equalsIgnoreCase("Ship Upgrades"))
  343.           System.out.println(stock.get(i) + "\n");
  344.       }
  345.     }
  346.     else if (cata == 2) // if user chooses category "2"
  347.     {
  348.       for (int i = 0; i < stock.size(); i++) // loops through stock looking for items of category "WEAPONS"
  349.       {
  350.         if ((stock.get(i).getCatagory()).equalsIgnoreCase("Weapons"))
  351.           System.out.println(stock.get(i) + "\n");
  352.       }
  353.     }
  354.     else if (cata == 3) // if user chooses category "3"
  355.     {
  356.       for (int i = 0; i < stock.size(); i++) // loops through stock looking for items of category "TOOLS"
  357.       {
  358.         if ((stock.get(i).getCatagory()).equalsIgnoreCase("Tools"))
  359.           System.out.println(stock.get(i) + "\n");
  360.       }
  361.     }
  362.   }
  363.  
  364.   private static void displayInvCategories() // displays item categories and prompts user to input a choice
  365.   {
  366.     System.out.println("1) Ship Upgrades");
  367.     System.out.println("2) Weapons");
  368.     System.out.println("3) Tools\n");
  369.     System.out.print("Enter a choice from above: ");
  370.   }
  371.  
  372.   private static int getInput(Scanner key) // gets user input method (uses try catch block for validation )
  373.   {
  374.     String inp;
  375.     int selection;
  376.     do // Loops while the user's input is not between 1 and 10
  377.     {
  378.       inp = key.nextLine();
  379.       try
  380.       {
  381.         selection = Integer.parseInt(inp);
  382.       }
  383.       catch (NumberFormatException e) // if the user does not input an integer
  384.       {
  385.         System.out.print("Please enter an integer!: ");
  386.         selection = -1;
  387.       }
  388.     }while(selection == -1);
  389.  
  390.     return selection;
  391.   }
  392.  
  393.   private static void displayMenu() // display main menu method
  394.   {
  395.     System.out.println("1) Create Empty Shopping Cart");
  396.     System.out.println("2) Add item to Shopping Cart");
  397.     System.out.println("3) Remove item from Shopping Cart");
  398.     System.out.println("4) Check Out\n");
  399.     System.out.print("Enter a number from above: ");
  400.   }
  401.  
  402.   private static ArrayList<Item> setupStock(ArrayList<Item> inv) // sets up array list of items
  403.   {
  404.     String dummyString;
  405.     int i = 0;
  406.     int dummyInt;
  407.     double dummyDouble;
  408.  
  409.     try
  410.     {
  411.       FileReader reader = new FileReader("storeItems.txt");     // Sets up file reader
  412.       BufferedReader buffReader = new BufferedReader(reader); // Sets up buffer reader
  413.  
  414.       // this loop inputs data from file into item object while there is data in the file or integer i is less than 15
  415.       /*
  416.        * NOTE: If the text file is in the incorrect format this will result in an incorrect format (ie. item category being the item name and so forth)
  417.       */
  418.       while (((dummyString = buffReader.readLine()) != null) || (i < 15))
  419.       {
  420.         inv.get(i).setNum(Integer.parseInt(dummyString));
  421.         dummyString = buffReader.readLine();
  422.         inv.get(i).setQuantity(Integer.parseInt(dummyString));
  423.         dummyString = buffReader.readLine();
  424.         inv.get(i).setName(dummyString);
  425.         dummyString = buffReader.readLine();
  426.         inv.get(i).setCatagory(dummyString);
  427.         dummyString = buffReader.readLine();
  428.         inv.get(i).setPrice(Double.parseDouble(dummyString));
  429.         i++;
  430.       }
  431.     }
  432.     // If the file is not found
  433.     catch(FileNotFoundException ex)
  434.     {
  435.       System.out.println("File not found!");
  436.     }
  437.     // If the file is broken
  438.     catch(IOException ex)
  439.     {
  440.       System.out.println("File Broken! Pls Fix!");
  441.     }
  442.     return inv; // Returns setup array to the main
  443.   }
  444. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement