How do I fix the addToCart method of the class? - java

I have to create code for an addToCart method to add an item to the itemList. I have looked at the other ShoppingCart problems on here, but I do not see one that adds to the quantity of the item and checks the name of the items to see if it is in the array...
The problem is
1) if an item with the name passed in the parameter already exists in the itemList, update that items quantity by increasing it by the quantity passed in.
2) if no item name exists in itemList and there is space for a new item, create a new item object with the given name, quantity, and price passed in as parameter, update numItems by 1.
3) both cases should return true.
4) if the item with the given name was not in the array and the array has no capacity the method should return false...
5) complete the dispay method to print out the name, total price, and quantity of each item in the itemList
I made a getItemIndex method, and am not sure if i need to use that within this method. As i have looked at the other addtoCart methods, I think that this one is different.
I have tried a for loop and it did not return what i wanted, so i have created new objects, but i cannot get the objects to stay contained in the array of objects.
Items class
public class Items{
private String name;
private double price;
private int quantity;
public Items (String n, double p, int q){
name = n;
price = p;
quantity = q;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public int getQuantity(){
return quantity;
}
public void addQuantity(int amt){
int newQuantity = amt + quantity;
quantity = newQuantity;
}
public String toString(){
return "item name: " + name + ", item quantity: " + quantity +
", total price: " + (price * quantity);
}
}
ShoppingCart class
public class ShoppingCart{
//TODO: declare a cart of Items
private Items[] itemList;
//TODO: declare the number of distinct items in the cart
private int numItems = 0;
private static final int INITIAL_CAP = 5; // the initial size of the cart
private static final int GROW_BY=3;
// ---------------------------------------------------------
// Creates an empty shopping cart with a capacity for 5 items.
// ---------------------------------------------------------
public ShoppingCart(){
itemList = new Items[INITIAL_CAP];
numItems = 0;
}
public double getTotalPrice(){
double totalPrice = 0;
numItems = 0;
for(int i = 0; i<itemList.length; i++){
if(itemList[i]!= null){
totalPrice = totalPrice + (itemList[i].getQuantity()*itemList[i].getPrice());
numItems++;
}
}
return totalPrice;
}
private int getItemIndex(String nameOfItem){
for(int i = 0; i < itemList.length; i++){
if(itemList[i].getName().equals(nameOfItem))
return i;
}
return -1;
}
public boolean addToCart(String name, double price, int quantity){
Items n = new Items (name, price, quantity);
if(numItems == INITIAL_CAP)
return false;
itemList[numItems]=n;
if(itemList[numItems].getName().equals(name)){
quantity = quantity + 1;
return true;
}
else if (!itemList[numItems].getName().equals(name)){
numItems = numItems + 1;
return true;
}
return false;
}
public String display(){
for(int i = 0; i<numItems; i++){
System.out.println(itemList[i].toString());
}
return toString();
}
}
The result should put the items into the array and stay contained in there, so when I call it in my main method it will stay in the array and it should print like this when i call it
milk $3.00 1 $3.00
eggs $3.00 1 $3.00
etc...
That will be printed b my simulation method, but i cannot figure out how to get the items to stay in the cart.

There are a couple issues here. First, you're setting itemList[numItems] before you've even checked if the name of the item passed to addToCart already exists in the items list. Second, you don't check the entire list, you only check the element at index numItems, which will always evaluate to true in this case since you set itemList[numItems] to the new item before checking if the name already exists. To resolve this, I would suggest running a for loop, from i = 0 to numItems, and checking for the existence of the name of the new item. Once you've confirmed that it does not exist, then add the new item and increment numItems. If the item already exists, however, then update the quantity and return. Lastly, the check to see if the item list is full should be done after you've iterated the entire list to see if the item already exists. The reason for this is that because you need to update existing item quantities even if the list is full. So before trying to add a new item, you should check if there is enough space in the list.
public boolean addToCart(String name, double price, int quantity){
Items n = new Items (name, price, quantity);
for(int i = 0; i < numItems; i++){
if(itemList[i].getName().equals(name)) {
itemList[i].quantity += quantity;
return true;
}
}
if(numItems == INITIAL_CAP)
return false;
itemList[numItems] = n;
numItems += 1;
return true;
}

Related

Arrays with mutliple elements in java and other Issue

Having problems linking this program to this class. The program takes in a set of String + double arrays and goes through a series of sorts to yield a result. Our instructions are to sort then by name and sort then by price.
Main problem is that the Strings are displaying as hexadecimal eg(Item#4fjipe) etc.
Second problem is my sorts. I just have no idea how to make them work. Please help if at all possible. I will include both the class and the program. Bear in mind they are 2 different .java working together. I'm a beginner, by the way.
public class Item
{
private String itemName; // hold the name of the item
private double itemPrice; // hold the price of the item
public Item(String s, double p) // Constructor
{
itemName = s;
itemPrice = p;
}//end constructor
public void setName(String n)
{//method to set the item name
itemName = n;
}//end method
public String getName()
{//method to get the item name
return itemName;
}//end method
public double setPrice(double p1)
{//method to set the price of the item
itemPrice = p1;
return itemPrice;
}//end method
public double getPrice()
{//method to get the price of the item
return itemPrice;
}//end method
}//end class
AND NOW THE OTHER BEGINS. THIS ONE IS STILL A HOT MESS.
import javax.swing.*;
import java.util.Arrays;
public class CoffeeDriver
{
public static void main (String[] args)
{
Item[] itemArray = new Item[5]; // Array of type Item declaration
boolean loopControl = false; //variable for control of our loop
while (!loopControl)
{
itemArray[0] = new Item("Coffee", 1.00);
itemArray[1] = new Item("Water", 2.00);
itemArray[2] = new Item("Milk", 1.50);
itemArray[3] = new Item("Bagel",1.25);
itemArray[4] = new Item("Donut", 0.75);
String input = JOptionPane.showInputDialog(null, "Welcome to Wings Coffee Shop. We have a great list items on our menu. \nWould you like to see these items sorted by name of by price? (n/p):");
if(input.equals("n"))
{
sortName(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}//end if
else if(input.equals("p"))
{
sortPrice(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}
else
{
loopControl = true;
}
}//end while
}//end main
public static void sortName(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortName
public static void sortPrice(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortPrice
}//end class
You need to override the toString method in your Item class. You could use:
#Override
public String toString() {
return "Item [itemName=" + itemName + ", itemPrice=" + itemPrice + "]";
}
As you need to have 2 separate methods to sort by name and by price, you could use a custom comparator for both cases, using the appropriate field to compare against. Have a look at Arrays.sort() for doing the actual sorting.
'Item#4fjipe' is the object reference as provided by the default implementation of Object.toString() - read the API for reference.
A hexadecmial literal in Java start swith 0x, e.g. 0x10.
For your specific problem, you have a data object that you wish to sort in 2 different ways. Read the API documentation for Comparator and Comparable. Then check the Collections API to see which collections might offer you sorting.

How to write GetItemIndex method

I am creating a ShoppingCart class that represents a shopping cart. I am good with the basics of the class and the getTotalPrice method, but I cannot figure out how to do the getItemIndex problem...
"Complete the getItemIndex method as follow: if the itemList has an item with the name passed into the parameter, return the index of that item in the array. Otherwise return -1. "
I know i have to call the Items class, but I do not understand how I can get the name from the item class and return the index.
I have created the Items class and the instance variables and constructor of the ShoppingCart class. I have looked at other shopping Cart methods, but I could not find one that does the getItemIndex
i Tried the code included in the bottom called getItemIndex... I included the getTotalPrice in case it is needed as a reference.
public class ShoppingCart{
private Items[] itemList;
//TODO: declare the number of distinct items in the cart
private int numItems = 0;
private static final int INITIAL_CAP = 5; // the initial size of the
cart
private static final int GROW_BY=3;
// ---------------------------------------------------------
// Creates an empty shopping cart with a capacity for 5 items.
// ---------------------------------------------------------
public ShoppingCart(){
itemList = new Items[INITIAL_CAP];
numItems = 0;
}
public double getTotalPrice(){
double totalPrice = 0;
numItems = 0;
for(int i = 0; i<itemList.length; i++){
if(itemList[i]!= null){
totalPrice = totalPrice + (itemList[i].getQuantity()*itemList[i].getPrice());
numItems++;
}
}
return totalPrice;
}
private int getItemIndex(){
if(itemList(itemList.getName))
return Items[itemList.getName];
else
return -1;
}
}
Here is the items class
public class Items{
private String name;
private double price;
private int quantity;
public Items (String n, double p, int q){
name = n;
price = p;
quantity = q;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public int getQuantity(){
return quantity;
}
public void addQuantity(int amt){
int newQuantity = amt + quantity;
quantity = newQuantity;
}
public String toString(){
return "item name: " + name + ", item quantity: " + quantity + ", total price: " + (price * quantity);
}
}
I expect a method that is an if statement, but I am not sure how to get the ItemIndex...I am not sure if this requires a for loop either. In another class, I will call this method to use it to simulate a shopping experience.
This should works. You specify nameOfItem you are trying to find. Then iterate through all items in array, if its in array, returns index.
int getItemIndex(String nameOfItem){
for(int i = 0; i < itemList.length; i++){
if(itemList[i].getName().equals(nameOfItem){
return i;
}
}
return -1;
}

How do I access the itemPrice part of this array?

So I need to grab the itemPrice part of the index and add them all together, but i'm not sure how to go about accessing that. Can I somehow use my getCost method from the GroceryItemOrder class and continuously add it to the totalCost in the GroceryList class, or do I need to access the itemPrice and quantity part of each stored object.
public class GroceryList {
public GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
public int manyItems;
public GroceryList() {
final int INITIAL_CAPACITY = 10;
groceryList = new GroceryItemOrder[INITIAL_CAPACITY];
manyItems = 0;
}
//Constructs a new empty grocery list array
public GroceryList(int numItem) {
if (numItem < 0)
throw new IllegalArgumentException
("The amount of items you wanted to add your grocery list is negative: " + numItem);
groceryList = new GroceryItemOrder[numItem];
manyItems = 0;
}
public void add(GroceryItemOrder item) {
if (manyItems <= 10) {
groceryList[manyItems] = item;
}
manyItems++;
}
//
// #return the total sum list of all grocery items in the list
public double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ ) {
//THIS PART
}
return totalCost;
}
}
And this is GroceryItemOrder
public class GroceryItemOrder {
public String itemName;
public int itemQuantity;
public double itemPrice;
public GroceryItemOrder(String name, int quantity, double pricePerUnit) {
itemName = name;
itemQuantity = quantity;
itemPrice = pricePerUnit;
}
public double getcost() {
return (itemPrice*itemQuantity);
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public String toString() {
return (itemName + " " + itemQuantity);
}
}
Thanks for all the replies! I got it working and understand what's going on here now.
You first need to access an instance of GroceryItemOrder in the array and from there then access its itemPrice field like so,
groceryList[0].itemPrice
would give you the itemPrice of the first groceryListOrder in the groceryList array. If you want to use a method to do this instead, then add a getItemPrice method in your groceryListOrder class,
public getItemPrice() {
return itemPrice;
}
Then you can access each groceryListOrder's itemPrice in the array like so,
groceryList[0].getItemPrice()
would do the same as groceryList[0].itemPrice. If you wanna get the total cost of all the objects in the groceryList array, then use a loop to add all the itemPrice fields multiplied by the itemQuantity field (since it's the totalcost of each object being summed together) by using your getcost method,
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
totalCost += groceryList[i].getcost();
}
First of all you should encapsulate all fields ofGroceryItemOrder class, so all the fields should be private member of the class and then use their setter/getter methods to access them in GroceryList.
Secondly, this implementation has a bug. The second constructor gets numItem as input and initialize array size accordingly. But, add method does not look at the real size and that might cause invalid array index exception. Consider this code:
GroceryList list = new GroceryList(2);
for (int i=0; i<10; i++)
list.add(new GroceryItemOrder("grocery", 5, 10));
The exception will be occurred when i=2
This works for me, you would need to set static GroceryItemOrder[] groceryList = new GroceryItemOrder[0]; as well:
//
// #return the total sum list of all grocery items in the list
public static double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ )
{
totalCost += groceryList[i].getcost();
}
return totalCost;
}

How to calculate total sum of JList elements?

I'm creating a shopping cart simulation with a list of products as my inventory and a list used as the shopping cart which the user can scan items into. This, in theory, is to display the total cost as items in a JTextField below the list as they are being added to the basket.
To scan the items I have the following method :
public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;
//Iterate to get the price of the new items.
for (int i = 0; i < list.getModel().getSize(); i++) {
CartItem item = (CartItem) list.getModel().getElementAt(i);
totalAddedValue += Double.ParseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
string cartFieldText = cartTotalField.getText();
//Check that cartTextField already contains a value.
if(cartTextField != null && !cartTextField.isEmpty())
{
oldCartValue = Double.parseDouble(cartFieldText);
}
cartTotalField.setText(String.valueOf(oldCartValue + totalAddedValue));
checkoutBasket.addElement(list);
}
Currently my main issue is that scanning one item into the cart will display the sum total of all items in the inventory list rather than just the one item I'm trying to scan. It will also print a line under the item name as such javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... . How could I get around this issue ?
ItemList Class
public class StockList extends DefaultListModel {
public StockList(){
super();
}
public void addItem(String barcodeNo, String itemName, String price){
super.addElement(new Item(barcodeNo, itemName, price));
}
public Item findItemByName(String name){
Item temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (Item)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (Item)super.elementAt(indexLocation);
}
}
public Item findItemByBarcode(String id){
Item temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (CheckoutItem)super.elementAt(i);
if (temp.getBarcodeNo().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (Item)super.elementAt(indexLocation);
}
}
public void Item(String id){
Item empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... .
That is the toString() representation of a JList. The JList default renderer just invokes the toString() method of any object added to the ListModel.
checkoutBasket.addElement(list);
Don't add the JList to the checkout basket. You have to add each item in the list to the checkout basket separately.

Get total cost from arraylist

I don't know how to get total cost from this code ..........The PurchaseList class should use an array field to store the purchased items, as well as keeping track of its size (number of items in the list so far).
A PurchaseList class should have the following methods:
PurchaseList( ) //Constructs a new empty purchase list.
public void add(ItemPrice item) //Adds the given purchase item to this list, if the list is not full(i.e., has fewer than 10 items).
public double getTotalCost( ) //Returns the total sum cost of all purchased item in this list.
Write another class named ItemPrice that represents the price of an item according to quantity. The ItemPrice class should store an item quantity and a price per unit. An ItemPrice object should have the following methods:
ItemPrice(String name, int quantity, double pricePerUnit) //Constructs a purchased item with the given name, quantity and price per unit.
public double getCost( ) //Returns the total cost of this item only in its given quantity.
public void setQuantity(int quantity) //Sets this purchase item’s quantity to be the given value.
lastly create test class;
this is my code;
import java.util.ArrayList;
import java.util.List;
class PurchaseList{
double totalcost = 0;
private ArrayList<ItemPrice> itemlist;
PurchaseList(){
itemlist = new ArrayList<ItemPrice>(10);
}
public void add(ItemPrice item){
itemlist.add(item);
}
public double getTotalCost(){
for (ItemPrice pricelist : itemlist) {
totalcost += pricelist.getCost();
}
return totalcost;
}
}
class ItemPrice{
String name;
int quantity;
double pricePerUnit;
ItemPrice(String name, int quantity, double pricePerUnit){
this.name=name;
this.quantity=quantity;
this.pricePerUnit=pricePerUnit;
}
public double getCost(){
return pricePerUnit*quantity;
}
public void setQuantity(int quantity){
this.quantity=quantity;
}
}
public class TestPurchase{
private double item;
public static void main (String[] args) {
PurchaseList test = new PurchaseList();
ItemPrice itm =new ItemPrice("Milo",4,20.00);
ArrayList<ItemPrice> itemlist= new ArrayList<ItemPrice>();
itemlist.add(itm);
System.out.println(itm.quantity+" item(s) of "+itm.name +" is RM "+itm.getCost()+". Each item is priced at RM " + itm.pricePerUnit);
ItemPrice itm1 =new ItemPrice("Milk",4,5.00);
itm1.setQuantity(1);
itemlist.add(itm1);
System.out.println(itm1.quantity+" item(s) of "+itm1.name +" is RM "+itm1.getCost()+". Each item is priced at RM " + itm1.pricePerUnit);
System.out.println("The Total cost of item in this list is RM "+test.getTotalCost());
}
}
thank you!!!!!!
First, itemlist is null (and you don't initialize it in your constructor), so this
private ArrayList<ItemPrice> itemlist;
should be something like
private List<ItemPrice> itemlist = new ArrayList<>();
Then you can either keep a running total as items are added to the list like
public void add(ItemPrice item){
itemlist.add(item);
totalcost += item.getCost();
}
or you could iterate the ItemPrice(s) and calculate the total when getTotalCost() is called.
public double getTotalCost() {
double total = 0;
for (ItemPrice ip : itemlist) {
total += ip.getCost();
}
return total;
}
Well since you have an accessor method, getCost() you could use that and add each value in the arraylist to a variable. That variable could then be used to return a totalcost of all the itemprices in your arraylist.
public double getTotalCost()
{
double totalcost = 0;
//BE SURE TO START TOTAL COST AT ZERO OR IT CANNOT ADD UP!!!
for(int i = 0; i < itemlist.size(); i++)
{
totalCost += itemlist.get(i).getCost();
}
//DON'T DO IT IN THE FOR LOOP OR THE RETURN STATEMENT WILL STOP IT!
return totalCost;
}

Resources