1 Replies - 284 Views - Last Post: 17 May 2014 - 04:03 PM Rate Topic: -----

#1 wolfninja  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 11-May 14

How to write the itemsInCart list to a file?

Posted 14 May 2014 - 07:37 PM

Main:

package shoppingcartselection;

import javax.swing.*;
import java.util.ArrayList;

public class Main
{
    public static void main(String[] args)
    {
        ArrayList<Item> items = new ArrayList<>();

        // Sets the look and feel of the GUI to match the system
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException | ClassNotFoundException e)
        {
            e.printStackTrace();
        }

        if(Item.loadItems(items, "ItemPrices.txt"))
        {
            new ShoppingCartSelection(items);
        }
    }
}



Item:

package shoppingcartselection;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * Represents an item in a store. Includes methods of accessing the item's name
 * and retail price.
 *
 * @author Cody Williams
 */

public class Item
{
    /** The item's name */
    private String name;
    /** The item's retail price */
    private double retailPrice;

    /**
     * Set's the item's name and retail price to the values given.
     *
     * @param name The item's name
     * @param retailPrice The item's retail price
     */
    
    public Item(String name, double retailPrice)
    {
        setName(name);
        setRetailPrice(retailPrice);
    }

    /** Returns the item's name */
    public String getName()
    {
        return name;
    }

    /** Returns the item's retail price */
    public double getRetailPrice()
    {
        return retailPrice;
    }

    /** Sets the item's name to the value given */
    public void setName(String name)
    {
        this.name = name;
    }

    /** Sets the item's retail price to the value given */
    public void setRetailPrice(double retailPrice)
    {
        this.retailPrice = retailPrice;
    }

    /**
     * Loads the contents of ItemPrices.txt into an ArrayList
     *
     * @param items The ArrayList of items to be read into.
     * @param fileName The name of the file to be read.
     * @return If loading the file was successful or not.
     */
    public static boolean loadItems(ArrayList<Item> items, String fileName)
    {
        try(Scanner scanner = new Scanner(new File(fileName)))
        {
            String currentLine;
            String deliminators = ", ";
            String[] tokens;

            scanner.useDelimiter(", ");

            while(scanner.hasNext())
            {
                currentLine = scanner.nextLine();
                tokens = currentLine.split(deliminators);
                items.add(new Item(tokens[0], Double.parseDouble(tokens[1])));
            }

            return true;
        }
        catch(FileNotFoundException e)
        {
            JOptionPane.showMessageDialog(
                    null,
                    "Error opening " + fileName + "! \n\nMake sure that it is in the same directory as the program.",
                    "File Not Found", JOptionPane.ERROR_MESSAGE
            );

            return false;
        }
    }
}



ShoppingCartSelection:

package shoppingcartselection;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Cody Williams
 */

public class ShoppingCartSelection extends JFrame
{
    private JPanel itemPanel;
    private JPanel selectedItemPanel;
    private JPanel buttonPanel;
    private JList<String> itemList;
    private JList<String> selectedItemList;
    private JScrollPane scrollPane1;
    private JScrollPane scrollPane2;
    private JButton addToCartButton;
    private JButton removeFromCartButton;
    private JButton clearCartButton;
    private JButton checkoutButton;
    /**
     * Contains the contents of itemList
     */
    private DefaultListModel<String> itemListModel = new DefaultListModel<String>();
    /**
     * Contains the contents of selectedItemList
     */
    private DefaultListModel<String> selectedItemListModel = new DefaultListModel<String>();
    /**
     * All of the items loaded from file
     */
    private ArrayList<Item> items;
    /**
     * Decimal formatter. Used to format decimal amounts.
     */
    DecimalFormat decimalFormat = new DecimalFormat("####.##");
    /**
     * The items that are in the cart.
     */
    ArrayList<Item> itemsInCart = new ArrayList<>();
    /**
     * The names of the items that are in the cart.
     */
    String[] itemsInCartNames;
    /**
     * The percentage of sales tax.
     */
    double SALES_TAX_PERCENTAGE = 0.075;
    /**
     * The subtotal of the purchase at checkout.
     */
    double subtotal;
    /**
     * The sales tax on the purchase at checkout.
     */
    double salesTax;
    /**
     * The total amount due at checkout.
      */
    double total;

    /**
     * Constructor
     */
    public ShoppingCartSelection(ArrayList<Item> items)
    {
        this.items = items;

        // Populates itemListModel
        for(int index = 0; index < items.size(); index++)
        {
            itemListModel.add(index, items.get(index).getName());
        }

        // Configures basics of window
        setTitle("Item Selection");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Builds panels
        buildItemPanel();
        buildSelectedItemPanel();
        buildButtonPanel();

        // Adds the panels to the content pane
        add(itemPanel, BorderLayout.NORTH);
        add(selectedItemPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // Packs and displays the window
        pack();
        setVisible(true);
    }

    /**
     * Adds a list containing the names of the items to a panel.
     */
    private void buildItemPanel()
    {
        itemPanel = new JPanel();
        itemList = new JList<>(itemListModel);
        itemList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        itemList.setVisibleRowCount(14);
        scrollPane1 = new JScrollPane(itemList);
        itemPanel.add(scrollPane1);
    }

    /**
     * Adds a list to a panel. This will hold the selected item's names.
     */
    private void buildSelectedItemPanel()
    {
        selectedItemPanel = new JPanel();
        selectedItemList = new JList<>(selectedItemListModel);
        selectedItemList.setVisibleRowCount(6);
        scrollPane2 = new JScrollPane(selectedItemList);
        selectedItemPanel.add(scrollPane2);
    }

    /**
     * Adds buttons to the buttonPanel and assigns action listeners..
     */
    private void buildButtonPanel()
    {
        buttonPanel = new JPanel();
        addToCartButton = new JButton("Add");
        removeFromCartButton = new JButton("Remove");
        clearCartButton = new JButton("Clear");
        checkoutButton = new JButton("Checkout");
        addToCartButton.addActionListener(new AddToListButtonListener());
        removeFromCartButton.addActionListener(new RemoveFromCartButtonListener());
        clearCartButton.addActionListener(new ClearCartButtonListener());
        checkoutButton.addActionListener(new CheckoutButtonListener());
        buttonPanel.add(addToCartButton);
        buttonPanel.add(removeFromCartButton);
        buttonPanel.add(clearCartButton);
        buttonPanel.add(checkoutButton);
    }

    /**
     * Checks for user selections in the item list. If the user has selected something, then that item is added to the
     * selected item list and removed from the item list. If the user has not selected anything, then a dialog is
     * created that tells the user that they must select something first.
     */
    private class AddToListButtonListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if(itemList.getSelectedIndices().length > 0)
            {
                int[] selectedIndices = itemList.getSelectedIndices();

                for(int index = selectedIndices.length - 1; index >= 0; index--)
                {
                    selectedItemListModel.add(0, itemListModel.get(selectedIndices[index]));
                    itemListModel.removeElementAt(selectedIndices[index]);
                }
            }
            else
            {
                JOptionPane.showMessageDialog(
                        null,
                        "You must select something first!",
                        "No Selections Found",
                        JOptionPane.ERROR_MESSAGE
                );
            }
        }
    }

    /**
     * Checks for user selections in the selected item list. If the user has selected something, then that item is
     * added to the item list and removed from the selected item list. If the user has not selected anything, then a
     * dialog is created that tells the user that they must select something first.
     */
    private class RemoveFromCartButtonListener implements ActionListener
    {
        
        @Override
        public void actionPerformed(ActionEvent e)
        {
            // If the user has selected something, then add it to the tem list and remove it from the selected tem list
            if(selectedItemList.getSelectedIndices().length > 0)
            {
                int[] selectedIndices = selectedItemList.getSelectedIndices();

                for(int index = selectedIndices.length - 1; index >= 0; index--)
                {
                    itemListModel.add(0, selectedItemListModel.get(selectedIndices[index]));
                    selectedItemListModel.removeElementAt(selectedIndices[index]);
                }
            }
            else
            {
                JOptionPane.showMessageDialog(
                        null,
                        "You must select something first!",
                        "No Selections Found",
                        JOptionPane.ERROR_MESSAGE
                );
            }
        }
    }

    /**
     * If there are values in the selected item list model, then it adds them to the item list model and removes them
     * from the selected item list model, effectively clearing the cart.
     */
    private class ClearCartButtonListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if(selectedItemListModel.getSize() != 0)
            {
                int selectedItemListModelSize = selectedItemListModel.getSize();

                for(int index = 0; index < selectedItemListModelSize; index++)
                {
                    itemListModel.add(0, selectedItemListModel.get(0));
                    selectedItemListModel.removeElementAt(0);
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "The cart is empty!", "Empty Cart", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private class CheckoutButtonListener implements ActionListener, Serializable
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            if(selectedItemListModel.size() != 0)
            {
                // Sets itemsInCartNames to the contents of selectedItemListModel
                itemsInCartNames = Arrays.copyOf(selectedItemListModel.toArray(), selectedItemListModel.toArray().length,
                        String[].class);

                // Adds item objects to itemsInCart
                for(String itemsInCartName : itemsInCartNames)
                {
                    for(Item item : items)
                    {
                        if(itemsInCartName.equals(item.getName()))
                        {
                            itemsInCart.add(item);
                        }
                    }
                }
                

                // Calculates subtotal from items in itemsInCart
                for(Item aItemsInCart : itemsInCart)
                {
                    subtotal += aItemsInCart.getRetailPrice();
                }

                // Calculates the salesTax
                salesTax = subtotal * SALES_TAX_PERCENTAGE;

                // Calculates total
                total = subtotal + salesTax;

                // Displays message dialog with subtotal, salesTax, and total
                JOptionPane.showMessageDialog
                (
                        null,
                        "Subtotal: $" + decimalFormat.format(subtotal) +
                        "\nSales Tax: $" + decimalFormat.format(salesTax) +
                        "\nTotal: $" + decimalFormat.format(total),
                        "Purchase Successful!", JOptionPane.INFORMATION_MESSAGE
                );
                
                 JOptionPane.showMessageDialog
                (
                        null,
                        "Your receipt has been saved to Receipt.txt",                        
                        "Thank You, Come Again!", JOptionPane.INFORMATION_MESSAGE                         
                );
                 
                try {
                    save(itemsInCart);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(ShoppingCartSelection.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
            else
            {
                JOptionPane.showMessageDialog(null, "The cart is empty!", "Empty Cart", JOptionPane.ERROR_MESSAGE);
            }           
        } 
        
        public void save(ArrayList Receipt) throws FileNotFoundException 
        {
         PrintWriter pw = new PrintWriter(new FileOutputStream("Receipt.txt"));
         
         pw.println("Subtotal: $" + decimalFormat.format(subtotal));
         pw.println("Sales Tax: $" + decimalFormat.format(salesTax));
         pw.println("\nTotal: $" + decimalFormat.format(total));
         pw.close();
        }
    }
}



I have it to save to a text file the subtotal, sales tax, and the total cost of all items in the cart after clicking on Checkout. I need it to also show the Items that where in the cart, along with how much each Item costs. I've tried this:

        public void save(ArrayList Receipt) throws FileNotFoundException 
        {
         PrintWriter pw = new PrintWriter(new FileOutputStream("Receipt.txt"));
         for (Item itemsInCartNames : itemsInCart)
         pw.println(itemsInCartNames);
         pw.close();
        }



But this is what gets saved to the Receipt.txt file:

shoppingcartselection.Item@16752c9


itemPices.txt:

Magic Booster Pack, 4
Magic Fat Pack, 40
Magic Intro Deck, 12
Magic Duel Deck, 20
Magic Card Sleeves, 8
Magic Play Mat, 25
Magic Booster Box, 120
Dice Pack, 6
Video Game, 60
Book, 10
Candy, 1
Soda, 1
Lunch, 10
Water, 1
Shirt, 10
Hat, 5
Game Console, 400
Desktop, 800
Laptop, 1000

Is This A Good Question/Topic? 0
  • +

Replies To: How to write the itemsInCart list to a file?

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2777
  • View blog
  • Posts: 11,758
  • Joined: 20-September 08

Re: How to write the itemsInCart list to a file?

Posted 17 May 2014 - 04:03 PM

You need to override toString in Item
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1