Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Author: Jacob Gallucci
- E-mail: [email protected]
- Course: CMPSC 221
- Assignment: Programming Assignment 3 - Store Shopping Cart - Main
- Due date: 4/2/2018
- File: pawnShop.java
- Purpose: Driver for Item.java .. Allows user to add items to their cart, remove items from their cart and check out
- Compiler/IDE: OpenJDK 1.8.0_151 (compiled from CLI) - Atom / Vim text editors
- Operating system: Debian Stretch 9
- Reference(s):
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html - Arraylist documentation
- https://www.geeksforgeeks.org/arraylist-in-java/ - Arraylist examples (used to get the proper format and such)
- */
- import java.io.*;
- import java.util.*;
- import java.text.NumberFormat;
- public class pawnShop
- {
- public static void main(String[] args) // Main
- {
- ArrayList<Item> shopStock = new ArrayList<Item>(15); // Shop stock, contains 15 items (object)
- ArrayList<Item> cart = new ArrayList<Item>(); // User cart, Note: Initialized Here
- Scanner keyboard = new Scanner(System.in); // keyboard scanner - user input
- int input; // Integer for input
- int itemChoice; // Item choice when adding items to cart / deleting items from cart
- int quan; // Quantity to add to cart / remove from cart
- boolean cartExists = false; // If the cart is not created, this is false and you cannot add stuff to a cart
- for (int i = 1; i <= 15; i++) // initializes the shop's stock
- shopStock.add(new Item());
- setupStock(shopStock); // Adds items from .txt file to the stock
- System.out.println("Welcome to Ants in My Eyes Johnson's InterGalactic Pawn Shop!\n");
- do // Main do loop
- {
- displayMenu(); // displays main menu
- do // user input loop, loops while the user selection is not in range of the menu options
- {
- input = getInput(keyboard); // gets input from user
- if ((input < 1) || (input > 4)) // if the input is outside of the range of the menu
- System.out.println("Please Input a number from above!");
- }while((input < 1) || (input > 4));
- if (input == 1) // creates cart
- {
- cartExists = true;
- System.out.println("Cart Created!");
- }
- else if ((input == 2) && cartExists) // Adds item to cart (if cart exists)
- {
- do // Loops while out of range of menu (1-3)
- {
- displayInvCategories(); // Displays categories of items
- input = getInput(keyboard); // gets input of which category the individual wants to purchase from
- if ((input < 1) || (input > 3)) // if input is out of range (1-3)
- System.out.println("Please Input a number from above!");
- }while((input < 1) || (input > 3));
- displayItems(input, shopStock); // Displays items of the selected category
- System.out.print("Enter the product number of your desired item: ");
- itemChoice = getInput(keyboard); // gets user's desired item by product code
- if (validItem(itemChoice, shopStock)) // If the item is valid
- {
- if (getQuantity(itemChoice, shopStock) > 0) // If the item is in stock
- {
- quan = getQuantity(itemChoice, shopStock); // stores # of items in stock
- System.out.print("Enter quantity of item (Max: " + quan + "): ");
- do // Loops while user's quantity is less than 0 or greater than # of items in stock
- {
- input = getInput(keyboard); // gets user's desired quantity
- if (input > quan)
- System.out.println("Invalid amount! We don't have enough in stock!");
- else if (input < 0)
- System.out.println("You can't magically add stuff to the stock by purchasing negative amounts!");
- }while (input > quan || input < 0);
- addItemToCart(input, itemChoice, cart, shopStock); // adds item to cart
- System.out.println("Item successfully Added to your cart!\n");
- displayCart(cart); // displays updated cart
- }
- else // if item quantity = 0
- System.out.println("Item is temporarily out of stock!");
- }
- 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
- System.out.println("Invalid Product Code!");
- }
- else if ((input == 3) && cartExists && !cart.isEmpty()) // Deletes item from cart
- {
- displayCart(cart); // displays cart
- System.out.print("Enter the item number of the product you wish to remove from the cart: ");
- itemChoice = getInput(keyboard); // gets user input for item they wish to remove
- if (validItem(itemChoice, cart)) // if the item is valid
- {
- quan = getQuantity(itemChoice, cart); // gets quantity of item in cart
- System.out.print("Enter the quantity you wish to remove from the cart (Max: " + quan + "): ");
- do // loops while input is out of range of quantity in the cart
- {
- input = getInput(keyboard);
- if ((input > quan) || (input < 0))
- System.out.println("Invalid amount! Enter a valid quantity: ");
- }while ((input > quan) || (input < 0));
- removeFromCart(input, itemChoice, cart, shopStock); // removes item from cart
- System.out.println("Successfully removed item from cart!");
- }
- else // if the item is not in the cart
- System.out.println("Item does not exist in your cart!");
- }
- else if ((input == 4) && cartExists && !(cart.isEmpty())) // if the user wishes to check out
- {
- checkout(cart, keyboard); // calls checkout method
- }
- else if ((input == 4) && (cart.isEmpty()) && cartExists) // if the user wants to check out but their cart is empty
- {
- System.out.println("Your cart is empty!!! Buy something!");
- input = -1;
- }
- else if ((input != 1) && !cartExists) // if the user wants to do ANYTHING and the cart doesn't exist
- {
- System.out.println("Cart Doesn't Exist! Type '1' to create one!");
- input = -1;
- }
- }while(input != 4);
- System.exit(0); // ends program
- }
- ///////////////////////////////////////////////METHODS///////////////////////////////////////////////////////////
- private static void checkout(ArrayList<Item> userCart, Scanner keys) // Checkout method
- {
- double cost = 0.0; // cost of cart
- String name = ""; // Card holder name
- String cardType = ""; // Card type
- String expirationDate = ""; // expiration date of the card
- String cardNum = ""; // credit card number
- boolean validExpire = false; // used to determine if the expiration date of the card is a valid date
- boolean validCard = false; // used to determine if the Credit card is 16 integers in length
- Locale locale = new Locale("en", "US"); // sets currency locale to USA
- NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(locale); // sets number format to USA
- displayCart(userCart); // Displays cart
- System.out.println("These are the items you are purchasing...");
- for (int i = 0; i < userCart.size(); i++) // Sums the price of the the cart
- cost = cost + userCart.get(i).getPrice() * userCart.get(i).getQuantity();
- cost = cost * 1.10; // adds tax
- System.out.println("Total Cost + Intergalactic Federation Tax (10%): " + moneyFormat.format(cost) + "\n");
- System.out.print("Enter Card Holder Name: ");
- name = keys.nextLine(); // gets user's name
- do // Loops while card type is invalid
- {
- System.out.print("Enter Card Type (Visa / Mastercard / InterStellar): ");
- cardType = keys.nextLine(); // gets card type
- if (!(cardType.equalsIgnoreCase("VISA")) && !(cardType.equalsIgnoreCase("MASTERCARD")) && !(cardType.equalsIgnoreCase("INTERSTELLAR")))
- System.out.println("Invalid Card Type!");
- }while(!(cardType.equalsIgnoreCase("VISA")) && !(cardType.equalsIgnoreCase("MASTERCARD")) && !(cardType.equalsIgnoreCase("INTERSTELLAR")));
- do // loops while the inputted format of the expiration date is invalid
- {
- System.out.print("Enter card expiration date (MM/YY): ");
- expirationDate = keys.nextLine(); // gets expiration date from the user
- validExpire = checkExp(expirationDate); // checks id expiration date is valid
- if (!validExpire) // if the expiration date is invalid
- System.out.println("Invalid expiration date!");
- }while (!validExpire);
- do // Loops while the credit card number is not valid
- {
- System.out.print("Input your 16 digit card number: ");
- cardNum = keys.nextLine(); // gets user card number
- if (!cardIsInt(cardNum) || cardNum.length() != 16) // checks if the card number is all integers and if the card number length is not 16
- {
- validCard = false;
- System.out.println("Invalid Card Number!");
- }
- else
- validCard = true;
- }while(!validCard);
- System.out.println("\nProcessing your order...\n");
- // Outputs billing information
- System.out.println("Card Holder: " + name);
- System.out.println("Card Type: " + cardType);
- System.out.println("Card Number: " + cardNum);
- System.out.println("Card Expiration Date: " + expirationDate);
- System.out.println("_______________________________________________");
- System.out.println("Total Charged: " + moneyFormat.format(cost));
- 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!");
- return;
- }
- private static boolean cardIsInt(String card) // determines if card number consists of integers
- {
- for (int i = 0; i < card.length(); i++) // Loops through card number string
- {
- if (!Character.isDigit(card.charAt(i))) // if the character at i in the card number string isn't a digit returns FALSE
- return false;
- }
- return true; // returns true if passes all tests
- }
- private static boolean checkExp(String userExp) // Checks if expiration date is valid
- {
- int monthTens = 0;
- int monthOnes = 0;
- if (userExp.length() != 5) // checks if expiration date is a valid length (5)
- return false;
- else if (userExp.charAt(2) != '/') // checks if the middle character is a '/'
- return false;
- // checks if every non '/' character is a digit
- if (!Character.isDigit(userExp.charAt(0)) || !Character.isDigit(userExp.charAt(1)) || !Character.isDigit(userExp.charAt(3)) || !Character.isDigit(userExp.charAt(4)))
- return false;
- monthTens = Character.getNumericValue(userExp.charAt(0)); // gets month tens digit
- monthOnes = Character.getNumericValue(userExp.charAt(1)); // gets month ones digit
- if ((((monthTens * 10) + monthOnes) > 12) || ((monthTens * 10) + monthOnes) < 1 ) // if month digit is greater 12 or less than 1
- return false;
- return true; // if passes all tests, returns true
- }
- private static void removeFromCart(int quantityToRemove, int itemToRemove, ArrayList<Item> userCart, ArrayList<Item> stock) // remove from cart function
- {
- int i = 0; // i and j are incrementers used in do loop
- int j = 0;
- boolean backToStock = false;
- boolean removedFromCart = false;
- do // Loops while it's not removed from cart (don't worry, we've already checked if the item is valid!)
- {
- if (!(userCart.isEmpty()) && (itemToRemove == userCart.get(i).getNum())) // if the cart's not empty and item current item (i) is the item to remove
- {
- userCart.get(i).setQuantity(userCart.get(i).getQuantity() - quantityToRemove); // cart's item quantity is removed by the amount the user whishes to remove
- if (userCart.get(i).getQuantity() == 0) // if quantity = 0, just remove the object from the cart array list
- userCart.remove(i);
- do // loops while item is not back in stock
- {
- if (itemToRemove == stock.get(j).getNum()) // if the item to remove is the same as the current item in the stock (j)
- {
- stock.get(j).setQuantity(stock.get(j).getQuantity() + quantityToRemove); // adds quantity back to the stock
- backToStock = true; // adds item back into stock
- }
- j++;
- }while(!backToStock);
- removedFromCart = true; // removed from cart is set to true
- }
- i++;
- }while(!removedFromCart);
- }
- private static void displayCart(ArrayList<Item> userCart) // display cart
- {
- for (int i = 0; i < userCart.size(); i++) // loops through whole cart and displays each item
- {
- System.out.println(userCart.get(i));
- System.out.println("\n");
- }
- }
- private static void addItemToCart(int amount, int itemToAdd, ArrayList<Item> userCart, ArrayList<Item> stock) // adds item to cart
- {
- int i = 0;
- int j = 0;
- boolean inCart = false;
- do // Loops while item has not been added to the cart and i is less than stock size
- {
- if (itemToAdd == stock.get(i).getNum()) // if current item is the stock is the item to add (i)
- {
- stock.get(i).setQuantity(stock.get(i).getQuantity() - amount); // removes the amount to add to the cart from the stock
- if (!(userCart.isEmpty())) // if the cart is not empty
- {
- do // Loops through cart to check if the item is already in it
- {
- if (itemToAdd == userCart.get(j).getNum()) // if item is already in cart
- inCart = true;
- else
- j++;
- }while((!inCart) && (j < userCart.size()));
- }
- if (!inCart || userCart.isEmpty()) // if the item is not in the cart, add a new item to the cart
- userCart.add(new Item(itemToAdd, amount, stock.get(i).getName(), stock.get(i).getCatagory(), stock.get(i).getPrice()));
- else // if it's already int he cart just increase the quantity
- userCart.get(j).setQuantity(userCart.get(j).getQuantity() + amount);
- }
- i++;
- }while((!inCart) && (i < stock.size()));
- }
- private static int getQuantity(int choice, ArrayList<Item> stock) // get quantity of item method
- {
- int i = 0;
- int quantityOfItem = -1;
- do // Loops through stock /cart to get the quantity of the item in the respective thing
- {
- if (choice == stock.get(i).getNum()) // if item is found
- quantityOfItem = stock.get(i).getQuantity(); // stores the quantity in quantityOfItem
- i++;
- }while((quantityOfItem == -1) && i < stock.size());
- return quantityOfItem; // returns quantity of the item in cart / stock
- }
- private static boolean validItem(int choice, ArrayList<Item> stock) // determines if the item is a valid item
- {
- boolean inStock = false;
- 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
- {
- if (choice == stock.get(i).getNum()) // if item is found
- inStock = true;
- }
- return inStock; // returns whether or not the item is in the cart
- }
- private static void displayItems(int cata, ArrayList<Item> stock) // displays the items of their respective categories
- {
- System.out.println("\n");
- if (cata == 1) // if user chooses category "1"
- {
- for (int i = 0; i < stock.size(); i++) // loops through stock looking for item of category "SHIP UPGRADES"
- {
- if ((stock.get(i).getCatagory()).equalsIgnoreCase("Ship Upgrades"))
- System.out.println(stock.get(i) + "\n");
- }
- }
- else if (cata == 2) // if user chooses category "2"
- {
- for (int i = 0; i < stock.size(); i++) // loops through stock looking for items of category "WEAPONS"
- {
- if ((stock.get(i).getCatagory()).equalsIgnoreCase("Weapons"))
- System.out.println(stock.get(i) + "\n");
- }
- }
- else if (cata == 3) // if user chooses category "3"
- {
- for (int i = 0; i < stock.size(); i++) // loops through stock looking for items of category "TOOLS"
- {
- if ((stock.get(i).getCatagory()).equalsIgnoreCase("Tools"))
- System.out.println(stock.get(i) + "\n");
- }
- }
- }
- private static void displayInvCategories() // displays item categories and prompts user to input a choice
- {
- System.out.println("1) Ship Upgrades");
- System.out.println("2) Weapons");
- System.out.println("3) Tools\n");
- System.out.print("Enter a choice from above: ");
- }
- private static int getInput(Scanner key) // gets user input method (uses try catch block for validation )
- {
- String inp;
- int selection;
- do // Loops while the user's input is not between 1 and 10
- {
- inp = key.nextLine();
- try
- {
- selection = Integer.parseInt(inp);
- }
- catch (NumberFormatException e) // if the user does not input an integer
- {
- System.out.print("Please enter an integer!: ");
- selection = -1;
- }
- }while(selection == -1);
- return selection;
- }
- private static void displayMenu() // display main menu method
- {
- System.out.println("1) Create Empty Shopping Cart");
- System.out.println("2) Add item to Shopping Cart");
- System.out.println("3) Remove item from Shopping Cart");
- System.out.println("4) Check Out\n");
- System.out.print("Enter a number from above: ");
- }
- private static ArrayList<Item> setupStock(ArrayList<Item> inv) // sets up array list of items
- {
- String dummyString;
- int i = 0;
- int dummyInt;
- double dummyDouble;
- try
- {
- FileReader reader = new FileReader("storeItems.txt"); // Sets up file reader
- BufferedReader buffReader = new BufferedReader(reader); // Sets up buffer reader
- // this loop inputs data from file into item object while there is data in the file or integer i is less than 15
- /*
- * 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)
- */
- while (((dummyString = buffReader.readLine()) != null) || (i < 15))
- {
- inv.get(i).setNum(Integer.parseInt(dummyString));
- dummyString = buffReader.readLine();
- inv.get(i).setQuantity(Integer.parseInt(dummyString));
- dummyString = buffReader.readLine();
- inv.get(i).setName(dummyString);
- dummyString = buffReader.readLine();
- inv.get(i).setCatagory(dummyString);
- dummyString = buffReader.readLine();
- inv.get(i).setPrice(Double.parseDouble(dummyString));
- i++;
- }
- }
- // If the file is not found
- catch(FileNotFoundException ex)
- {
- System.out.println("File not found!");
- }
- // If the file is broken
- catch(IOException ex)
- {
- System.out.println("File Broken! Pls Fix!");
- }
- return inv; // Returns setup array to the main
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement