For my java midterm i had a question which i missed major points on and still do
ID: 3662371 • Letter: F
Question
For my java midterm i had a question which i missed major points on and still dont know how to make it work! please help and make this run as its supposed to! Basically, given the font end (GUI) you have to write the back end to make the program work. here is the question : You are to
write a set of supporting classes for a simple shopping cart.
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!!!!!
File Edit View Window Help 2 | / 6 | - + | 7596 Tools Fill & Sign Comment 75% | Item object stores information about an individual item. It must have the following public methods. Note that the names (such as price and bulk quantity) given here are not meant to be the actual parameter names (Checkstyle would complain about them); they re meant to be descriptive Method Descri Constructor that takes a name and a price as arguments. The name is a Item(name, price) String and the price is a BigDecimal Item(name, price, Constructor that takes a name, a single-item price, a bulk quantity, and a bulk quantity, bulkbulk price as arguments. The name is a string, the quantity is an int and the Returns the single item ce s are BigDecimal S. e for this Item. (BigDecimal retun for this Item. int retum tv getPrice() getBulkQuantity) Returns the bulk getBulkPrice)Retums the bulk price for this Item. (Bi retum Retums True if the Item has bulk pricing: false otherwise Returns a string representation of this Item: name, followed by a comma and a space, followed by price. If the item has a bulk price, you should append an extra space and a parenthesized description of the bulk pricing that has the bulk quantity, the word "for" and the bulk price. See the Returns true if the specified object is equivalent to this Item, and false otherwise. Two items are equivalent if they have exactly equivalent names, prices, bulk quantities and bulk prices. This method must properly override java.lang.object.equals() Returns an integer hash code for this item. This method must override java.lang.object.hashCode () and be consistent with equals isBulk() toString() les below equals (object) names, prices, hashCode() The string representation of an Item must exactly match that shown in the screenshots. For example, an Item named X" with a per-item price of $19.99 and no bulk quantity would have the string representation "x, 19.99" (without the quotes); an item named X" with a per-item price of $19.99, a bulk quantity of 5 and a bulk price of $89.99 would have the string representation "x, 19.99 (5 for $89.99)" (without the quotes). The format of these String representations will be tested. An ItemOrder object stores infomation about a purchase order for a particular item: namely, a reference to the item itself and the quantity desired. It must have the following public methods Method ItemOrder (item, Description Constructor that creates an item order for the given quantity of the given Item. The quantity, 1s an int Returns a reference to the Item in this ItemOrder Returns the quantity for this ItemOrder Returns a String representation of this ItemOrder: You may use any format that seems reasonable to vou for this String tin getIten() getQuantity() tostring()Explanation / Answer
/*
002. * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
003. *
004. * You may not modify, use, reproduce, or distribute this software
005. * except in compliance with the terms of the license at:
006. * http://developer.sun.com/berkeley_license.html
007. */
008.
009.package cart;
010.
011.import entity.Product;
012.import java.util.*;
013.
014./**
015. *
016. * @author tgiunipero
017. */
018.public class ShoppingCart {
019.
020. List<ShoppingCartItem> items;
021. int numberOfItems;
022. double total;
023.
024. public ShoppingCart() {
025. items = new ArrayList<ShoppingCartItem>();
026. numberOfItems = 0;
027. total = 0;
028. }
029.
030. /**
031. * Adds a <code>ShoppingCartItem</code> to the <code>ShoppingCart</code>'s
032. * <code>items</code> list. If item of the specified <code>product</code>
033. * already exists in shopping cart list, the quantity of that item is
034. * incremented.
035. *
036. * @param product the <code>Product</code> that defines the type of shopping cart item
037. * @see ShoppingCartItem
038. */
039. public synchronized void addItem(Product product) {
040.
041. boolean newItem = true;
042.
043. for (ShoppingCartItem scItem : items) {
044.
045. if (scItem.getProduct().getId() == product.getId()) {
046.
047. newItem = false;
048. scItem.incrementQuantity();
049. }
050. }
051.
052. if (newItem) {
053. ShoppingCartItem scItem = new ShoppingCartItem(product);
054. items.add(scItem);
055. }
056. }
057.
058. /**
059. * Updates the <code>ShoppingCartItem</code> of the specified
060. * <code>product</code> to the specified quantity. If '<code>0</code>'
061. * is the given quantity, the <code>ShoppingCartItem</code> is removed
062. * from the <code>ShoppingCart</code>'s <code>items</code> list.
063. *
064. * @param product the <code>Product</code> that defines the type of shopping cart item
065. * @param quantity the number which the <code>ShoppingCartItem</code> is updated to
066. * @see ShoppingCartItem
067. */
068. public synchronized void update(Product product, String quantity) {
069.
070. short qty = -1;
071.
072. // cast quantity as short
073. qty = Short.parseShort(quantity);
074.
075. if (qty >= 0) {
076.
077. ShoppingCartItem item = null;
078.
079. for (ShoppingCartItem scItem : items) {
080.
081. if (scItem.getProduct().getId() == product.getId()) {
082.
083. if (qty != 0) {
084. // set item quantity to new value
085. scItem.setQuantity(qty);
086. } else {
087. // if quantity equals 0, save item and break
088. item = scItem;
089. break;
090. }
091. }
092. }
093.
094. if (item != null) {
095. // remove from cart
096. items.remove(item);
097. }
098. }
099. }
100.
101. /**
102. * Returns the list of <code>ShoppingCartItems</code>.
103. *
104. * @return the <code>items</code> list
105. * @see ShoppingCartItem
106. */
107. public synchronized List<ShoppingCartItem> getItems() {
108.
109. return items;
110. }
111.
112. /**
113. * Returns the sum of quantities for all items maintained in shopping cart
114. * <code>items</code> list.
115. *
116. * @return the number of items in shopping cart
117. * @see ShoppingCartItem
118. */
119. public synchronized int getNumberOfItems() {
120.
121. numberOfItems = 0;
122.
123. for (ShoppingCartItem scItem : items) {
124.
125. numberOfItems += scItem.getQuantity();
126. }
127.
128. return numberOfItems;
129. }
130.
131. /**
132. * Returns the sum of the product price multiplied by the quantity for all
133. * items in shopping cart list. This is the total cost excluding the surcharge.
134. *
135. * @return the cost of all items times their quantities
136. * @see ShoppingCartItem
137. */
138. public synchronized double getSubtotal() {
139.
140. double amount = 0;
141.
142. for (ShoppingCartItem scItem : items) {
143.
144. Product product = (Product) scItem.getProduct();
145. amount += (scItem.getQuantity() * product.getPrice().doubleValue());
146. }
147.
148. return amount;
149. }
150.
151. /**
152. * Calculates the total cost of the order. This method adds the subtotal to
153. * the designated surcharge and sets the <code>total</code> instance variable
154. * with the result.
155. *
156. * @param surcharge the designated surcharge for all orders
157. * @see ShoppingCartItem
158. */
159. public synchronized void calculateTotal(String surcharge) {
160.
161. double amount = 0;
162.
163. // cast surcharge as double
164. double s = Double.parseDouble(surcharge);
165.
166. amount = this.getSubtotal();
167. amount += s;
168.
169. total = amount;
170. }
171.
172. /**
173. * Returns the total cost of the order for the given
174. * <code>ShoppingCart</code> instance.
175. *
176. * @return the cost of all items times their quantities plus surcharge
177. */
178. public synchronized double getTotal() {
179.
180. return total;
181. }
182.
183. /**
184. * Empties the shopping cart. All items are removed from the shopping cart
185. * <code>items</code> list, <code>numberOfItems</code> and
186. * <code>total</code> are reset to '<code>0</code>'.
187. *
188. * @see ShoppingCartItem
189. */
190. public synchronized void clear() {
191. items.clear();
192. numberOfItems = 0;
193. total = 0;
194. }
195.
- See more at: https://netbeans.org/projects/samples/sources/samples-source-code/content/samples/javaee/AffableBean/src/java/cart/ShoppingCart.java#sthash.R96jgPEu.dpuf
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.