Given completed classes forming a gui, Create 3 classes for a shopping cart ( I
ID: 3662493 • Letter: G
Question
Given completed classes forming a gui, Create 3 classes for a shopping cart ( I have done below). Then fill in the missing methods IN THE CLASSES BELOW!!! I have already created the methods. more instructions found in the images below. Thanks! be sure to follow checkstyle requirements! FINISH THE Item.Java, ItemOrder.java and ShoppingCart.java classes below. Do NOT change any code in the other 3 classes (GUI). PERFECT ANSWERS GET A HIGH RATING!
Classes GIVEN : Note : CLASSES are SEPERATED BY Dashes (------------------------------------------------------------------------------)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import model.Item;
/**
* A utility class for The shopping cart application.
*
*/
public final class FileLoader {
/**
* A private constructor, to prevent external instantiation.
*/
private FileLoader() {
}
/**
* Reads item information from a file and returns a List of Item objects.
* @param theFile the name of the file to load into a List of Items
* @return a List of Item objects created from data in an input file
*/
public static List readItemsFromFile(final String theFile) {
final List items = new LinkedList<>();
try (Scanner input = new Scanner(Paths.get(theFile))) { // Java 7!
while (input.hasNextLine()) {
final Scanner line = new Scanner(input.nextLine());
line.useDelimiter(";");
final String itemName = line.next();
final BigDecimal itemPrice = line.nextBigDecimal();
if (line.hasNext()) {
final int bulkQuantity = line.nextInt();
final BigDecimal bulkPrice = line.nextBigDecimal();
items.add(new Item(itemName, itemPrice, bulkQuantity, bulkPrice));
} else {
items.add(new Item(itemName, itemPrice));
}
line.close();
}
} catch (final IOException e) {
e.printStackTrace();
} // no finally block needed to close 'input' with the Java 7 try with resource block
return items;
}
/**
* Reads item information from a file and returns a List of Item objects.
* @param theFile the name of the file to load into a List of Items
* @return a List of Item objects created from data in an input file
*/
public static List readConfigurationFromFile(final String theFile) {
final List results = new LinkedList<>();
try (Scanner input = new Scanner(Paths.get(theFile))) { // Java 7!
while (input.hasNextLine()) {
final String line = input.nextLine();
//if (!line.startsWith("#")) {
if (!(line.charAt(0) == '#')) {
results.add(line);
}
}
} catch (final IOException e) {
e.printStackTrace();
} // no finally block needed to close 'input' with the Java 7 try with resource block
return results;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
//import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
//import java.awt.image.BufferedImage;
import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
//import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
//import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import model.Item;
import model.ItemOrder;
import model.ShoppingCart;
/**
* ShoppingFrame provides the user interface for a shopping cart program.
*
*/
public final class ShoppingFrame extends JFrame {
/**
* The Serialization ID.
*/
private static final long serialVersionUID = 0;
// constants to capture screen dimensions
/** A ToolKit. */
private static final Toolkit KIT = Toolkit.getDefaultToolkit();
/** The Dimension of the screen. */
private static final Dimension SCREEN_SIZE = KIT.getScreenSize();
/**
* The width of the text field in the GUI.
*/
private static final int TEXT_FIELD_WIDTH = 12;
/**
* The color for some elements in the GUI.
*/
private static final Color COLOR_1 = new Color(199, 153, 0); // UW Gold
/**
* The color for some elements in the GUI.
*/
private static final Color COLOR_2 = new Color(57, 39, 91); // UW Purple
/**
* The shopping cart used by this GUI.
*/
private final ShoppingCart myItems;
/**
* The map that stores each campus name and the campus's bookstore inventory.
*/
private final Map> myCampusInventories;
/**
* The map that stores each campus name and the campus's bookstore inventory.
*/
private final String myCurrentCampus;
/**
* The text field used to display the total amount owed by the customer.
*/
private final JTextField myTotal;
/**
* The panel that holds the item descriptions. Needed to add and remove on
* the fly when the radio buttons change.
*/
// private JPanel myItemsPanel;
/**
* A List of the item text fields.
*/
private final List myQuantities;
/**
* Initializes the shopping cart GUI.
*
* @param theCampusInventories The list of items.
* @param theCurrentCampus The campus that is originally selected when
* the application starts.
*/
public ShoppingFrame(final Map> theCampusInventories,
final String theCurrentCampus) {
// create frame and order list
super(); // No title on the JFrame. We can set this later.
myItems = new ShoppingCart();
// set up text field with order total
myTotal = new JTextField("$0.00", TEXT_FIELD_WIDTH);
myQuantities = new LinkedList<>();
myCampusInventories = theCampusInventories;
myCurrentCampus = theCurrentCampus;
setupGUI();
}
/**
* Setup the various parts of the GUI.
*
*/
private void setupGUI() {
// hide the default JFrame icon
//final Image icon = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE);
// replace the default JFrame icon
final ImageIcon img = new ImageIcon("files/w.gif");
setIconImage(img.getImage());
setTitle("Shopping Cart");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// the following was used in autumn 2015, not in winter 2016
add(makeTotalPanel(), BorderLayout.NORTH);
final JPanel itemsPanel = makeItemsPanel(myCampusInventories.get(myCurrentCampus));
add(itemsPanel, BorderLayout.CENTER);
add(makeCheckBoxPanel(), BorderLayout.SOUTH);
// adjust size to just fit
pack();
// make the GUI so that it cannot be resized by the user dragging a corner
setResizable(false);
// position the frame in the center of the screen
setLocation(SCREEN_SIZE.width / 2 - getWidth() / 2,
SCREEN_SIZE.height / 2 - getHeight() / 2);
setVisible(true);
}
// /**
// * Creates the panel to hold the campus location radio buttons.
// *
// * @return The created JPanel
// */
// private JPanel makeCampusPanel() {
// final JPanel p = new JPanel();
// p.setBackground(COLOR_2);
//
// final ButtonGroup g = new ButtonGroup();
// for (final Object campus : myCampusInventories.keySet()) {
// final JRadioButton rb = new JRadioButton(campus.toString());
// rb.setForeground(Color.WHITE);
// rb.setBackground(COLOR_2);
// rb.setSelected(campus.equals(myCurrentCampus));
// g.add(rb);
// p.add(rb);
//
// //Java 8 use of Lambda Expression instead
// // of an anonymous inner ActionListener object
// rb.addActionListener(ae -> {
// myCurrentCampus = rb.getText();
//
// //remove the old panel and add the new one
// remove(myItemsPanel);
// myItemsPanel = makeItemsPanel(myCampusInventories.get(myCurrentCampus));
// add(myItemsPanel, BorderLayout.CENTER);
//
// //clear previous data from the ShppingCart and
// //update the total in the GUI
// myItems.clear();
// updateTotal();
//
// //redraw the UI with the new panel
// pack();
// revalidate();
// }
// );
// }
// return p;
// }
/**
* Creates a panel to hold the total.
*
* @return The created panel
*/
private JPanel makeTotalPanel() {
// tweak the text field so that users can't edit it, and set
// its color appropriately
myTotal.setEditable(false);
myTotal.setEnabled(false);
myTotal.setDisabledTextColor(Color.BLACK);
// create the panel, and its label
final JPanel totalPanel = new JPanel();
totalPanel.setBackground(COLOR_2);
final JLabel l = new JLabel("order total");
l.setForeground(Color.WHITE);
totalPanel.add(l);
totalPanel.add(myTotal);
final JPanel p = new JPanel(new BorderLayout());
//p.add(makeCampusPanel(), BorderLayout.NORTH);
p.add(totalPanel, BorderLayout.CENTER);
return p;
}
/**
* Creates a panel to hold the specified list of items.
*
* @param theItems The items
* @return The created panel
*/
private JPanel makeItemsPanel(final List theItems) {
final JPanel p = new JPanel(new GridLayout(theItems.size(), 1));
for (final Item item : theItems) {
addItem(item, p);
}
return p;
}
/**
* Creates and returns the checkbox panel.
*
* @return the checkbox panel
*/
private JPanel makeCheckBoxPanel() {
final JPanel p = new JPanel();
p.setBackground(COLOR_2);
final JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent theEvent) {
myItems.clear();
for (final JTextField field : myQuantities) {
field.setText("");
}
updateTotal();
}
});
p.add(clearButton);
final JCheckBox cb = new JCheckBox("customer has store membership");
cb.setForeground(Color.WHITE);
cb.setBackground(COLOR_2);
cb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent theEvent) {
myItems.setMembership(cb.isSelected());
updateTotal();
}
});
p.add(cb);
return p;
}
/**
* Adds the specified product to the specified panel.
*
* @param theItem The product to add.
* @param thePanel The panel to add the product to.
*/
private void addItem(final Item theItem, final JPanel thePanel) {
final JPanel sub = new JPanel(new FlowLayout(FlowLayout.LEFT));
sub.setBackground(COLOR_1);
final JTextField quantity = new JTextField(3);
myQuantities.add(quantity);
quantity.setHorizontalAlignment(SwingConstants.CENTER);
quantity.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent theEvent) {
quantity.transferFocus();
}
});
quantity.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(final FocusEvent theEvent) {
updateItem(theItem, quantity);
}
});
sub.add(quantity);
final JLabel l = new JLabel(theItem.toString());
l.setForeground(COLOR_2);
sub.add(l);
thePanel.add(sub);
}
/**
* Updates the set of items by changing the quantity of the specified
* product to the specified quantity.
*
* @param theItem The product to update.
* @param theQuantity The new quantity.
*/
private void updateItem(final Item theItem, final JTextField theQuantity) {
final String text = theQuantity.getText().trim();
int number;
try {
number = Integer.parseInt(text);
if (number < 0) {
// disallow negative numbers
throw new NumberFormatException();
}
} catch (final NumberFormatException e) {
number = 0;
theQuantity.setText("");
}
myItems.add(new ItemOrder(theItem, number));
updateTotal();
}
/**
* Updates the total displayed in the window.
*/
private void updateTotal() {
final double total = myItems.calculateTotal().doubleValue();
myTotal.setText(NumberFormat.getCurrencyInstance().format(total));
}
}
// end of class ShoppingFrame
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.EventQueue;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import model.Item;
import utility.FileLoader;
/**
* ShoppingMain provides the main method for a simple shopping cart GUI
* displayer and calculator.
*/
public final class ShoppingMain {
/**
* The filename of the file containing the items to display in the cart.
*/
private static final String CONFIG_FILE = "config.txt";
/**
* The local path of the configuration files.
*/
private static final String FILE_LOCATION = "files/";
/**
* The map that stores each campus name and the campus's bookstore invintory.
*/
private static final Map> CAMPUS_INVINTORIES = new HashMap<>();
/**
* A private constructor, to prevent external instantiation.
*/
private ShoppingMain() {
}
/**
* The main() method - displays and runs the shopping cart GUI.
*
* @param theArgs Command line arguments, ignored by this program.
*/
public static void main(final String... theArgs) {
final List campusNames =
FileLoader.readConfigurationFromFile(FILE_LOCATION + CONFIG_FILE);
String mainCampus = null;
for (final String campusName : campusNames) {
//used to remove a warning and allow campusName to be final
String alteredName = campusName;
//as defined in config.txt the campus with a * should be the "main" campus
if (campusName.charAt(0) == '*') {
//remove the *
alteredName = campusName.substring(1);
mainCampus = alteredName;
}
CAMPUS_INVINTORIES.put(
alteredName,
FileLoader.readItemsFromFile(FILE_LOCATION
+ alteredName.toLowerCase(Locale.ENGLISH) + ".txt"));
}
final String currentStore = mainCampus;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ShoppingFrame(CAMPUS_INVINTORIES, currentStore);
}
});
} // end main()
} // end class ShoppingMain
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NOW THESE ARE THE CLASSES I CREATED WITH THE CORRECT METHODS. YOU CANNOT CHANGE ANY OF THE METHOD NAMES I HAVE SET BECAUSE THEY ARE ALL CORRECT TO THE SPEC OF THE PROGRAM. THANKS!
MY CLASSES: NOTE : seperated by dashes ( -------------------------------------------------------------------)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.math.BigDecimal;
public final class Item {
public Item(final String theName, final BigDecimal thePrice) {
}
public Item(final String theName, final BigDecimal thePrice, final int theBulkQuantity,
final BigDecimal theBulkPrice) {
}
public BigDecimal getPrice() {
return null;
}
public int getBulkQuantity() {
return 0;
}
public BigDecimal getBulkPrice() {
return null;
}
public boolean isBulk() {
return false;
}
@Override
public String toString() {
return null;
}
@Override
public boolean equals(final Object theOther) {
return false;
}
@Override
public int hashCode() {
return 0;
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public final class ItemOrder {
public ItemOrder(final Item theItem, final int theQuantity) {
}
public Item getItem() {
return null;
}
public int getQuantity() {
return 0;
}
@Override
public String toString() {
return null;
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.math.BigDecimal;
public class ShoppingCart {
public ShoppingCart() {
}
public void add(final ItemOrder theOrder) {
}
public void setMembership(final boolean theMembership) {
}
public BigDecimal calculateTotal() {
return null;
}
public void clear() {
}
@Override
public String toString() {
return null;
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
PLEASE FINISH CLASSES : Item.java, ItemOrder.java and shoppingCart.java ( Last three classes posted above) Thanks! NOTE : in the GUI the "discount" button should give the appropriate discount!!!!!
Explanation / Answer
Answer:
Here in the answer only the required three classes and their respective unit test classes are provided.
The classes that are provided are Item.java, ItemOrder.java, ShoppingCart.java, ItemClassTest.java, ItemOrderTestCases.java and ShoppingCartTestCases.java.
Program code to copy:
//Item.java
//define the package model
package model;
import java.math.BigDecimal;
//define the class Item in the model package
public final class Item
{
// declare the required variable
String name;
BigDecimal price;
int quantity;
BigDecimal bulkPrice;
// constructor that throws explicit exception
public Item(final String theName, final BigDecimal thePrice) throws IllegalAccessException
{
if (thePrice.compareTo(BigDecimal.ZERO) > 0 && theName.isEmpty())
throw new IllegalAccessException("Please check the price and name");
else
{
name = theName;
price = thePrice;
quantity = 0;
bulkPrice = null;
}
}
// constructor that throws implicit exception
public Item(final String theName, final BigDecimal thePrice, final int theBulkQuantity,
final BigDecimal theBulkPrice)
{
try
{
if (thePrice == null || theName == null || theBulkPrice == null)
throw new NullPointerException();
}
catch (NullPointerException npe)
{
npe.printStackTrace();
}
finally
{
name = theName;
price = thePrice;
quantity = theBulkQuantity;
bulkPrice = theBulkPrice;
}
}
// getPrice() returns the BigDecimal object price
public BigDecimal getPrice()
{
return price;
}
// getBulkQuantity() returns the integer value quantity
public int getBulkQuantity()
{
return quantity;
}
// getBulkPrice() returns the BigDecimal object bulkPrice
public BigDecimal getBulkPrice()
{
return bulkPrice;
}
// isBulk() returns the boolean value
public boolean isBulk()
{
return ((bulkPrice != null) ? true : false);
}
@Override
public String toString()
{
String s = "";
s += name + ", $" + price;
if (isBulk())
s += " (" + quantity + " for $" + bulkPrice + ")";
return s;
}
@Override
public boolean equals(final Object theOther)
{
Item other = (Item) theOther;
if (this.name.equals(other.name) && this.price.equals(other.getPrice())
&& this.quantity == other.getBulkQuantity()
&& this.bulkPrice.equals(other.getBulkPrice()))
return true;
return false;
}
@Override
public int hashCode()
{
final int primeHash = 7;
int resultHash = 1;
resultHash = primeHash * resultHash + ((name == null) ? 0 : name.hashCode());
resultHash = primeHash * resultHash + ((price == null) ? 0 : price.hashCode());
resultHash = primeHash * resultHash + quantity;
resultHash = primeHash * resultHash + ((bulkPrice == null) ? 0 : bulkPrice.hashCode());
return resultHash;
}
}
ItemOrder.java
//define the package model
package model;
//define the class ItemOrder in the model package
public final class ItemOrder
{
// declare the required variable Item object
Item item;
// constructor
public ItemOrder(final Item theItem, final int theQuantity)
{
try
{
if (theItem == null)
throw new NullPointerException();
}
catch (NullPointerException npe)
{
npe.printStackTrace();
}
item = theItem;
item.quantity = item.getBulkQuantity() + theQuantity;
}
// getItem() returns the Item object
public Item getItem()
{
return item;
}
// getQuantity() returns the item objects quantity
public int getQuantity()
{
return item.getBulkQuantity();
}
@Override
public String toString()
{
String s = item.toString();
s += " Quantity: " + getQuantity();
return s;
}
}
ShoppingCart.java
//define the package model
package model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
//define the class ShoppingCart in the model package
public class ShoppingCart
{
// declare the required variables
List<ItemOrder> shopping_cart;
boolean membership;
BigDecimal total_cost;
// Constructor
public ShoppingCart()
{
shopping_cart = new ArrayList<ItemOrder>();
membership = false;
total_cost = new BigDecimal(0);
}
// add() method adds the ItemOrder object to the list
public void add(final ItemOrder theOrder)
{
boolean flag = false;
int index = 0;
try
{
if (theOrder == null)
throw new NullPointerException();
else
{
for (int i = 0; i < shopping_cart.size(); i++)
{
if (shopping_cart.get(i).getItem().equals(theOrder.getItem()))
{
flag = true;
index = i;
}
}
if (flag)
{
shopping_cart.add(index, theOrder);
}
else
shopping_cart.add(theOrder);
}
}
catch (NullPointerException npe)
{
npe.printStackTrace();
}
}
// setMembership() sets the membership status of the customer
public void setMembership(final boolean theMembership)
{
membership = theMembership;
}
// calculateTotal() computes the total cost of the items
// and returns the BigDecimal value
public BigDecimal calculateTotal()
{
BigDecimal cost = null;
BigDecimal quantity = null;
System.out.println(shopping_cart.size());
for (int i = 0; i < shopping_cart.size(); i++)
{
if (shopping_cart.get(i).getItem().isBulk())
{
cost = shopping_cart.get(i).getItem().getBulkPrice();
total_cost = total_cost.add(cost);
}
else
{
quantity = new BigDecimal(shopping_cart.get(i).getQuantity());
cost = shopping_cart.get(i).getItem().getPrice().multiply(quantity);
total_cost = total_cost.add(cost);
}
}
total_cost = total_cost.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(total_cost);
return total_cost;
}
// clear() clears all the list of items in the shopping_cart object
public void clear()
{
shopping_cart.clear();
}
@Override
public String toString()
{
String s = "";
for (int i = 0; i < shopping_cart.size(); i++)
{
s += shopping_cart.get(i).getItem().toString() + " ";
}
return s;
}
}
Unit-test case classes for the above classes.
//ItemClassTest.java
package model;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import org.junit.Test;
public class ItemClassTest
{
@Test
public void testCase1() throws IllegalAccessException
{
String name = "Pizza";
BigDecimal price = new BigDecimal(23.876);
Item item = new Item(name, price);
assertEquals("Pizza", item.name );
assertEquals(new BigDecimal(23.876), item.getPrice());
}
@Test
public void testCase2()
{
Item item = new Item("Pizza", new BigDecimal(5.50), 10, new BigDecimal(45.65));
assertEquals("Pizza", item.name );
assertEquals(new BigDecimal(5.50), item.getPrice());
assertEquals(10, item.getBulkQuantity());
assertEquals(new BigDecimal(45.65), item.getBulkPrice());
}
@Test
public void testCase3()
{
Item item = new Item("Pizza", new BigDecimal(5.50), 10, new BigDecimal(45.65));
Item item1 = new Item("Burger", new BigDecimal(15), 5, new BigDecimal(70.50));
assertEquals(false, item.equals(item1));
}
@Test
public void testCase4()
{
Item item = new Item(null, new BigDecimal(5.50), 10, new BigDecimal(45.65));
assertEquals(null, item.name );
assertEquals(new BigDecimal(5.50), item.getPrice());
assertEquals(10, item.getBulkQuantity());
assertEquals(new BigDecimal(45.65), item.getBulkPrice());
}
}
//ItemOrderTestCases.java
package model;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import org.junit.Test;
public class ItemOrderTestCases
{
@Test
public void testCase1()
{
Item item = new Item("Pizza", new BigDecimal(5.50), 10, new BigDecimal(45.65));
ItemOrder itemOrder = new ItemOrder(item, 5);
assertEquals(true, item.equals(itemOrder.getItem()));
}
@Test
public void testCase2()
{
Item item = new Item("Pizza", new BigDecimal(5.50), 10, new BigDecimal(45.65));
ItemOrder itemOrder = new ItemOrder(item, 5);
assertEquals(15, itemOrder.getQuantity());
}
}
//ShoppingCartTestCases.java
package model;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import org.junit.Test;
public class ShoppingCartTestCases
{
@Test
public void test() throws IllegalAccessException
{
ShoppingCart shopping = new ShoppingCart();
Item item;
ItemOrder itemOrder;
//Create objects of the ItemOrder and add to
the shopping
//cart class
item = new Item("Pizza", new BigDecimal(5.50));
itemOrder = new ItemOrder(item, 5);
shopping.add(itemOrder);
item = new Item("HotDogs", new BigDecimal(2.50));
itemOrder = new ItemOrder(item, 4);
shopping.add(itemOrder);
item = new Item("Burger", new BigDecimal(10.50));
itemOrder = new ItemOrder(item, 6);
shopping.add(itemOrder);
BigDecimal estimate = new BigDecimal(100.50).setScale(2, BigDecimal.ROUND_HALF_EVEN);;
assertEquals(estimate, shopping.calculateTotal());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.