I am doing a Java Application for a class and need help with errors that are coming up after running the app.
The app is supposed to allow the user to add an item to the shopping cart(item name, price, quantity). The user described item will be added to the shopping cart array, and then it will be printed out once it is successfully added.
The shopping cart has a max capacity of 5 items initially, but if the cart size is > 5, it will be increased + 3, via the increaseSize method.
As stated below, I believe that the addToCart method is not adding the user described item to the cart. That is why it is a null value within the toString method.
So, I basically need help with the addToCart method.
Please correct me if I am wrong. Thank you.
An output from running the app is as follows:
run:
Enter the name of the item: a
Enter the unit price: 2
Enter the quantity: 2
Exception in thread "main" java.lang.NullPointerException
at shop.ShoppingCart.toString(ShoppingCart.java:62)
at java.lang.String.valueOf(String.java:2854)
at java.io.PrintStream.println(PrintStream.java:821)
at shop.Shop.main(Shop.java:49)
Java Result: 1
Below is the ShoppingCart Class.
The toString method should not have any errors being produced, but I believe that the problem lies within the addToCart method.
// **********************************************************************
// ShoppingCart.java
//
// Represents a shopping cart as an array of items
// **********************************************************************
import java.text.NumberFormat;
public class ShoppingCart
{
private Item[] cart;
private int itemCount; // total number of items in the cart
private double totalPrice; // total price of items in the cart
private int capacity; // current cart capacity
// -----------------------------------------------------------
// Creates an empty shopping cart with a capacity of 5 items.
// -----------------------------------------------------------
public ShoppingCart()
{
capacity = 5;
cart = new Item[capacity];
itemCount = 0;
totalPrice = 0.0;
}
// -------------------------------------------------------
// Adds an item to the shopping cart.
// -------------------------------------------------------
public void addToCart(String itemName, double price, int quantity)
{
Item temp = new Item(itemName, price, quantity);
totalPrice += (price * quantity);
itemCount += quantity;
cart[itemCount] = temp;
if(itemCount==capacity)
{
increaseSize();
}
}
// -------------------------------------------------------
// Returns the contents of the cart together with
// summary information.
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String contents = "\nShopping Cart\n";
contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";
for (int i = 0; i < itemCount; i++)
contents += cart[i].toString() + "\n";
contents += "\nTotal Price: " + fmt.format(totalPrice);
contents += "\n";
return contents;
}
// ---------------------------------------------------------
// Increases the capacity of the shopping cart by 3
// ---------------------------------------------------------
private void increaseSize()
{
Item[] temp = new Item[capacity+3];
for(int i=0; i < capacity; i++)
{
temp[i] = cart[i];
}
cart = temp;
temp = null;
capacity = cart.length;
}
}
Below is the Shop Main.
The ArrayList is not in use at this time, but will be later once the toString errors are corrected.
package shop;
// ***************************************************************
// Shop.java
//
// Uses the Item class to create items and add them to a shopping
// cart stored in an ArrayList.
// ***************************************************************
import java.util.ArrayList;
import java.util.Scanner;
public class Shop
{
public static void main (String[] args)
{
ArrayList<Item> cart = new ArrayList<Item>();
Item item;
String itemName;
double itemPrice;
int quantity;
Scanner scan = new Scanner(System.in);
String keepShopping = "y";
ShoppingCart cart1 = new ShoppingCart();
do
{
System.out.print ("Enter the name of the item: ");
itemName = scan.next();
System.out.print ("Enter the unit price: ");
itemPrice = scan.nextDouble();
System.out.print ("Enter the quantity: ");
quantity = scan.nextInt();
// *** create a new item and add it to the cart
cart1.addToCart(itemName, itemPrice, quantity);
// *** print the contents of the cart object using println
System.out.println(cart1);
System.out.print ("Continue shopping (y/n)? ");
keepShopping = scan.next();
}
while (keepShopping.equals("y"));
}
}
Below is the Item Class:
package shop;
// ***************************************************************
// Item.java
//
// Represents an item in a shopping cart.
// ***************************************************************
import java.text.NumberFormat;
public class Item
{
private String name;
private double price;
private int quantity;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
// -------------------------------------------------------
// Return a string with the information about the item
// -------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (name + "\t" + fmt.format(price) + "\t" + quantity + "\t"
+ fmt.format(price*quantity));
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return price;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
// -------------------------------------------------
// Returns the quantity of the item
// -------------------------------------------------
public int getQuantity()
{
return quantity;
}
}
I believe the problem is caused by these two lines from addToCart():
itemCount += quantity;
cart[itemCount] = temp;
Unless quantity is 0, this means cart[0] will never contain anything. In fact, whatever the value of quantity, you will be leaving that many gaps in cart (e.g. if quantity is 2, cart[0] and cart[1] will be null).
Since an Item already includes the quantity, I believe you meant to do this:
cart[itemCount] = temp;
itemCount += 1;
This way the first item will be put in cart[0], the second in cart[1], and so on.
Another small piece of advice: if you are concatenating any object with a String, you don't need to call toString() on the object. Java will automatically call String.valueOf() on the object, which avoids a NullPointerException because it returns the String "null" instead. In this case, it might have helped you debug the problem because you would have noticed the null String appearing in your output. You would have to change your code to the following:
for (int i = 0; i < itemCount; i++)
contents += cart[i] + "\n";
public void addToCart(String itemName, double price, int quantity)
{
Item temp = new Item(itemName, price, quantity);
totalPrice += (price * quantity);
itemCount += quantity;
cart[itemCount] = temp;
if(itemCount==capacity)
{
increaseSize();
}
}
This code is broken. You try to add to cart at index itemCount. This will throw index out of bound execptions. basicly you increase the size of your cart to late.
This also causes a lot off empty places in your array. You do not add your next Item at the next place of your arra but you jump quantity places ahead. This causes some of the values in your array to be null. This is most likly causing the NullPointerExceütion in toString().
For how to implement this self growing list. You might want to take a look at the class ArrayList that comes with the JDK.
there are some other points i want to point out:
google javaDoc and use it instead of your own custom comments
replace your for-loop in toString() with a for-each-loop
The problem lies both in your addToCart method.
If you type this code:
ShoppingCart shopcart= new ShoppingCart();
shopcart.addToCart("foo", 3, 2);
The shopping cart will have the following attributes:
totalPrice=6
itemCount = 2;
cart = { null, null, foo, null, null};
The problem is that addToCart only modify the "itemcount" element of the array cart without considering the number of element added.
Moreover, cart[0] will stay at null forever.
You should remplace theses lines
itemCount += quantity;
cart[itemCount] = temp;
by
for ( int i =0 ; i<quantity;i++)
{
cart[itemCount+i] = temp;
}
itemCount += quantity;
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am working on an assignment for my computer science class where I create a program that simulates grocery shopping by creating a class that implements a shopping cart as an array of items. The tasks I must complete are as follows:
Complete the ShoppingCart class by doing the following:
a. Declare an instance variable cart to be an array of Items and instantiate cart in the constructor to be an array holding capacity
Items.
b. Fill in the code for the increaseSize method. Your code should be similar to that in Listing 7.8 of the text but instead of
doubling the size just increase it by 3 elements.
c. Fill in the code for the addToCart method. This method should add the item to the cart and update the totalPrice instance
variable (note this variable takes into account the quantity).
d. Compile your class.
Write a program that simulates shopping. The program should have a loop that continues as long as the user wants to shop. Each
time through the loop read in the name, price, and quantity of the item the user wants to add to the cart. After adding an item to
the cart, the cart contents should be printed. After the loop print a "Please pay ..." message with the total price of the items in the
cart.
At the moment I am stuck on the addToCart method. When I run the program it will allow input for the first item's information but then it displays the error "java.lang.NullPointerException" and stops working. What should I do to get my code to work properly? I would really appreciate some help with this. :)
Here is my code:
Shopping Cart
import java.text.NumberFormat;
public class ShoppingCart
{
private int itemCount; // total number of items in the cart
private double totalPrice; // total price of items in the cart
private int capacity; // current cart capacity
Item[] cart;
// -----------------------------------------------------------
// Creates an empty shopping cart with a capacity of 5 items.
// -----------------------------------------------------------
public ShoppingCart()
{
capacity = 5;
itemCount = 0;
totalPrice = 0.0;
}
// -------------------------------------------------------
// Adds an item to the shopping cart.
// -------------------------------------------------------
public void addToCart(String itemName, double price, int quantity)
{
Item temp = new Item(itemName, price, quantity);
totalPrice += (price * quantity);
for ( int i = 0 ; i < quantity; i++)
{
cart[itemCount + i] = temp;
}
itemCount += quantity;
if(itemCount==capacity)
{
increaseSize();
}
}
// -------------------------------------------------------
// Returns the contents of the cart together with
// summary information.
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String contents = "\nShopping Cart\n";
contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";
for (int i = 0; i < itemCount; i++)
contents += cart[i].toString() + "\n";
contents += "\nTotal Price: " + fmt.format(totalPrice);
contents += "\n";
return contents;
}
// ---------------------------------------------------------
// Increases the capacity of the shopping cart by 3
// ---------------------------------------------------------
private void increaseSize()
{
Item[] temp = new Item[cart.length + 3];
for (int num = 0; num < cart.length; num++)
{
temp[num] = cart[num];
cart = temp;
}
}
}
Item
import java.text.NumberFormat;
public class Item implements Comparable<Item>
{
private String name;
private double price;
private int quantity;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
// -------------------------------------------------------
// Return a string with the information about the item
// -------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (name + "\t" + fmt.format(price) + "\t" + quantity + "\t"
+ fmt.format(price*quantity));
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return price;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
// -------------------------------------------------
// Returns the quantity of the item
// -------------------------------------------------
public int getQuantity()
{
return quantity;
}
public int compareTo(Item other)
{
if(this.getPrice()*getQuantity() > other.getPrice()*other.getQuantity())
return 1;
else if (this.getPrice()*this.getQuantity() < other.getPrice()*other.getQuantity())
return -1;
else
return 0;
}
}
Shopping
//Simulates shopping by using the ShoppingCart and Item classes
import java.util.Scanner;
public class Shopping
{
public static void main(String[] args)
{
ShoppingCart cart = new ShoppingCart();
String keepShopping;
Item item;
String itemName;
double itemPrice;
double totalPrice = 0;
int quantity;
Scanner scan = new Scanner(System.in);
do
{
System.out.println("Enter the name of the item");
itemName = scan.next();
System.out.println("Enter the item's price");
itemPrice = scan.nextDouble();
System.out.println("Enter the quantity of the item");
quantity = scan.nextInt();
totalPrice = (itemPrice * quantity);
cart.addToCart(itemName, itemPrice, quantity);
System.out.println(cart.toString());
System.out.println("Would you like to continue shopping "
+ "(y/n)?");
keepShopping = scan.next();
}
while (keepShopping.equalsIgnoreCase("y"));
System.out.println("Please pay $" + totalPrice);
}
You are not intializing the variable cart
Try using cart = new Item[capacity];
Or something like that.
If your capacity can increase at a certain point why don't you change the variable cart to an arrayList ?
Like this :
List <Item> cart = new ArrayList<Item> ();
And in the method addToCart just use add in your loop like this : cart.add(temp);
Edit: you will have to import the corresponding Interface :
import java.util.ArrayList;
import java.util.List;
In your ShoppingCart class you never initialize your Item Array so it is null, so when you try and add something to that array you get the null pointer exception.
To fix this do something like this in your constructor
public ShoppingCart()
{
capacity = 5;
itemCount = 0;
totalPrice = 0.0;
//Does not have to be 10. Could be any number.
//Just makes sure to not go over 10 or you will have to use your increaseSize method
cart = new Item[10]
}
If you want to be fancy you could also do something like this (This is probably better)
public ShoppingCart(int size)
{
capacity = 5;
itemCount = 0;
totalPrice = 0.0;
cart = new Item[size]
}
I am starting to work on three classes at once and while doing so i have received the error message above. I am very confused on why it is showing. I'm new to java so it could be something very easy that i just can't see. I am getting the error on the shopping cart class under the addToCart method. I know this is alot of stuff to look at but i would really appreciate any and all help that i can get.
public class ShoppingCart
{
private int itemCount; //total number of items in the cart
private double totalPrice; //total price of items in the cart
private final int MAXSIZE = 100; // cart maximum capacity
private Item[]cart;
//creates an empty shopping cart
public ShoppingCart()
{
Item[]cart = new Item [MAXSIZE];
itemCount = 0;
totalPrice = 0.0;
}
//adds an item to the shopping cart
public void addToCart(String itemName, double price, int quantity)
{
cart[itemCount] = new Item(itemName, price, quantity);
totalPrice = (totalPrice + (quantity * price));
itemCount++;
}
//returns the contents on the cart together with summary information
public String toString()
{
String contents = "\nShopping Cart\n";
contents = contents + String.format("%-12s%-12s%-10s%-7s%n", "Item",
"Unit Price", "Quantity", "Item Total");
for(int i = 0; i<itemCount; i++)
contents = contents + cart[i].toString() + "\n";
contents = contents + String.format("%20s$ %.2fn","CurrentTotal:", totalPrice);
return contents;
}
}
import java.util.*;
public class Shop
{
public static void main (String[] args)
{
ShoppingCart myCart = new ShoppingCart();
Scanner kbd = new Scanner(System.in);
String itemName;
double itemPrice;
int quantity;
String keepShopping = "y";
do
{
System.out.print ("Enter the name of the item: ");
itemName = kbd.nextLine();
System.out.print ("Enter the unit price: ");
itemPrice = kbd.nextDouble();
System.out.print ("Enter the quantity: ");
quantity = kbd.nextInt();
myCart.addToCart(itemName, itemPrice, quantity);
System.out.print ("Continue shopping (y/n)? ");
keepShopping = kbd.next();
kbd.nextLine();
}
while (keepShopping.equals("y"));
System.out.println("Have a Nice Day!");
}
}
import java.text.NumberFormat;
public class Item
{
private String name;
private double unitPrice;
private int quantity;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
unitPrice = itemPrice;
quantity = numPurchased;
}
// -------------------------------------------------------
// Return a string with the information about the item
// -------------------------------------------------------
public String toString ()
{
return String.format("%-15s$%-8.2f%-11d$%-8.2f", name, unitPrice, quantity, unitPrice*quantity);
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return unitPrice;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
// -------------------------------------------------
// Returns the quantity of the item
// -------------------------------------------------
public int getQuantity()
{
return quantity;
}
}
Here you are declaring the cart array
private Item[]cart;
inside this constructor, you are initializing it
public ShoppingCart() {
Item[]cart = new Item [MAXSIZE];
itemCount = 0;
totalPrice = 0.0;
}
but when you attempt to access one of its elements here (cart[itemCount]) it throws a NullPointerException
public void addToCart(String itemName, double price, int quantity) {
cart[itemCount] = new Item(itemName, price, quantity);
totalPrice = (totalPrice + (quantity * price));
itemCount++;
}
This is because, although you are declaring the array properly, it goes right back to null as soon as the constructor is over. The scope of that instance is local to the constructor body itself.
Change
Item[] cart = new Item [MAXSIZE];
to
cart = new Item [MAXSIZE];
Then,
cart[itemCount] = new Item(itemName, price, quantity);
will no longer throw a NullPointerException, because cart's scope has been expanded to the entire class.
You get the NullPointer exception if you are trying to reference a variable that has not been declared/instantiated. For instance if you declared something like:
List newList;
Then tried doing:
newList.add(item);
It would thrown an exception because new list was never instantiated. If it is throwing it in the addToCart() function it is most likely because one of the variables you are using has not been declared or instantiated. I would debug and print out the value of each variable when you get to that function call to make sure they have a value associated with them. If they don't that may just be your problem.
Hi this program acts as if you are shopping in a grocery store. The only problem is that I'm having trouble getting the binary search down. It is suppose to search the array cart for the string that the person is looking for. However, its not quite working (meaning I'm not sure whats wrong). If you could just take a look and see if theres a noticeable problem, that'd be great. Thanks for the help!
import java.util.*;
public class shop
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String userAns,name;
int amount;
double price;
ShoppingCart newCart = new ShoppingCart();
System.out.println("Would you like to shop at Sam's Club?");
userAns = scan.nextLine();
if(userAns.equalsIgnoreCase("yes"))
{
while(userAns.equalsIgnoreCase("yes"))
{
System.out.println("Please type in the products name you would like to purchase:");
name = scan.next();
System.out.println("Please type in the number of products you would like to purchase");
amount = scan.nextInt();
System.out.println("Please type in the amount of money it costs:");
price = scan.nextDouble();
newCart.addToCart(name,price,amount);
System.out.println(newCart);
System.out.println("Would you like to continue shopping at Sam's Club?");
userAns = scan.next();
}
System.out.println("Would you like to check your cart for an item?");
String userScan = scan.next();
if(userScan.equalsIgnoreCase("yes"))
binarySearch(newCart);
}
else
System.out.println("Have a nice day!");
}
}
// **********************************************************************
// ShoppingCart.java
//
// Represents a shopping cart as an array of items
// **********************************************************************
import java.util.*;
import java.text.NumberFormat;
public class ShoppingCart
{
Scanner scan = new Scanner(System.in);
private int itemCount; // total number of items in the cart
private double totalPrice; // total price of items in the cart
private int capacity; // current cart capacity
Item[] cart;
int i = 0;
// -----------------------------------------------------------
// Creates an empty shopping cart with a capacity of 5 items.
// -----------------------------------------------------------
public ShoppingCart()
{
capacity = 5;
itemCount = 0;
totalPrice = 0.0;
cart = new Item[capacity];
}
// -------------------------------------------------------
// Adds an item to the shopping cart.
// -------------------------------------------------------
public void addToCart(String itemName, double price, int quantity)
{
if(i == cart.length)
{
increaseSize();
}
else
{
Item newItem = new Item(itemName, price, quantity);
cart[i] = newItem;
totalPrice = (price*quantity)+totalPrice;
itemCount++;
i++;
}
}
// -------------------------------------------------------
// Returns the contents of the cart together with
// summary information.
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String contents = "\nShopping Cart\n";
contents += "\nItem:\t\tUnit Price: \tQuantity:\t\tTotal:\n";
for(int i = 0; i < itemCount; i++)
contents += cart[i].toString() + "\n";
contents += "\nTotal Price: " + fmt.format(totalPrice);
contents += "\n";
return contents;
}
// ---------------------------------------------------------
// Increases the capacity of the shopping cart by 3
// ---------------------------------------------------------
private void increaseSize()
{
Item[] temp = new Item[cart.length+3];
for(int item=0; item < cart.length; item++)
{
temp[item] = cart[item];
}
cart = temp;
}
public void binarySearch()
{
System.out.println("Type in the object you would like to search for: ");
String object = scan.next();
int high = cart.length-1;
int low = 0;
int middle = (low+high)/2;
while(!(cart[middle].getName().equals(object)) && low<=high)
{
if((cart[middle].getName()).compareTo(object) > 0)
if(cart[middle].getName().equals(object))
high = middle-1;
else
low = middle+1;
middle = (low+high)/2;
}
if(cart[middle].getName().equals(object))
System.out.println("Your item is found!");
else
System.out.println("Your item is not found.");
}
}
I don't think this is the problem but I will add this next one just incase:
// ***************************************************************
// Item.java
//
// Represents an item in a shopping cart.
// ***************************************************************
import java.text.NumberFormat;
public class Item
{
private String name;
private double price;
private int quantity;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
// -------------------------------------------------------
// Return a string with the information about the item
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (name + "\t\t" + fmt.format(price) + "\t\t" + quantity + "\t\t"
+ fmt.format(price*quantity));
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return price;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
// -------------------------------------------------
// Returns the quantity of the item
// -------------------------------------------------
public int getQuantity()
{
return quantity;
}
}
I messed up trying to print out this array list what am I doing wrong I've tried multiple times but when ever it prints it outputs null.
import java.util.ArrayList;
import java.util.Arrays;
import java.text.NumberFormat;
import java.util.Scanner;
//Class header
public class ShoppingCart {
// Start of main method
public static <Item> void main(String[] args) {
// Declare and instantiate a variable that is an ArrayList that can hold
// Product objects
ArrayList<Product> item = new ArrayList<Product>();
// Declare necessary local variables here
String Name = null;
double Price = 0;
int Quantity = 0;
String Seller = null;
Scanner scan = new Scanner(System.in);
String Shop = "yes";
// Write a print statement that welcome's the customer to our shop
/**
*
* create a do while that will be keep looping as long as user wants to
* continue shopping
*/
Product im = new Product(Name, Price, Quantity, Seller);
// do while loop start
do {
// Ask user to enter product name and store it in appropriate local
// variable
System.out.print("Please Enter the Product Name: ");
Name = scan.next();
// Ask user to enter product price and store it in appropriate local
// variable
System.out.print("Please Enter the Price of the Product: ");
Price = scan.nextDouble();
// Ask user to enter quantity and store it in appropriate local
// variable
System.out.print("Please enter the Quantity: ");
Quantity = scan.nextInt();
// Ask user to enter product manufacturer name and store it in
// appropriate local variable
System.out.print("Please Enter the Manufacturer: ");
Seller = scan.next();
System.out.print("Would you like to continue shopping?");
Shop = scan.next();
// create a new Product object using above inputed values
Product item2 = new Product(Name, Price, Quantity, Seller);
// add above created Product to the ArrayList cart if Product has
// available stock
// if stock not available inform user requested product is out of
// stock
// Ask user whether wants to continue shopping
// set the do while loop to continue to loop if Yes option is
// selected
} while (Shop.equals("Yes"));
System.out.println("Product Unit Price Quantity SubTotal");
System.out.println(Name + " " + (Price) + " " + Quantity + " " + (Price * Quantity));
System.out.println("00"); System.out.println(item);
// do while loop end
// header for shopping cart contents
// print details of each product added to the ArrayList
// calculate total price of the shopping cart
// print the total price of the shopping cart
}// end of main method
}// end of Shop class
First of all, why are you doing this
public static <Item> void main(String[] args) {
SHould be
public static void main(String[] args) {
To print the ArrayLIst just do this
System.out.println("Name\tPrice\tQuantity\tSeller\tTotal")
for (Product p : item){
double total = p.price * p.quantity;
System.out.println(p.name + "\t" + p.price + "\t" p.quantity + "\t" + p.seller + "\t" + total);
}
But first you need to add something to the list
Product item2 = new Product(Name, Price, Quantity, Seller);
item.add(item2);
Or even a cleaner looking idea would be override the toString method in the Product class
public class Product {
String name;
String Seller;
double price;
int quantity;
public Product(String name, double price, int quantity, String seller){
this.name = name;
this.seller = seller;
this.price = price;
this.seller = seller;
}
public String toString(){
double total = p.price * p.quantity;
return name + "\t" + price + "\t" quantity + "\t" + seller + "\t" + total;
}
}
To print from list just do this.
for (Product p : item){
System.out.println(p);
}
its because you never add the item2 to the arraylist item
just add
item.add(item2)
There are quite a few errors in your program.
First off, the reason nothing is being printed when you try printing your arraylist is because you never add any element to your array list, to do so you must use the following method.
arrayListName.add(elementToAdd);
Secondly your main method is incorrect, instead of
public static <Item> void main(String[] args) {
it should be
public static void main (String[] args) {
I am working on an assignment and I have run into a few problems. Here is the Assignment Question and what I've done so far and my question.
Complete ShoppingCart.java as follows:
Declare and instantiate a variable cart to be an empty ArrayList that can hold Product objects. Remember to import ArrayList. Comments in the code indicate where these statements should go.
Fill in the required statements to write a loop that requests required information from the user regards to a product item, create a Product object using inputted information, and add the product to the ArrayList. Ensure user can enter information for multiple products by enabling loop to continue work based on whether user wants to continue shopping. Comments in the code indicate where these statements go.
Print the shopping cart contents by printing each product items stored in the ArrayList. Remember that Product object has toString method. Print the total price of the cart after printing shopping cart contents. Remember to format the output of total price, so that it prints in current format. Comments in the code indicate where these statements go.
Compile and run your program with following inputs (Provide output of your program)
First product as Bicycle Horn with unit price as 7.19, quantity as 2, and manufacturer as Klout.
Second product as Forerunner Watch with unit price as 140.89, quantity as 2, and manufacturer as Garmin.
Here is the code I've written:
//***************************************************************
//ShoppingCart.java
//
//Uses the Product class to create items and add them to a shopping
//cart stored in an ArrayList.
//***************************************************************
// import statements
import java.util.ArrayList;
import java.text.NumberFormat;
import java.util.Scanner;
//Class header
public class ShoppingCart {
//Start of main method
public static <Item> void main(String[] args){
//Declare and instantiate a variable that is an ArrayList that can hold Product objects
ArrayList<Product> item = new ArrayList<Product>();
//Declare necessary local variables here
String Name = null;
double Price = 0;
int Quantity = 0;
String Seller = null;
Scanner scan = new Scanner(System.in);
// Write a print statement that welcome's the customer to our shop
/**
* create a do while that will be keep looping as long as user wants to continue shopping
*/
String keepShopping = "Yes";
Product item1 = new Product(Name, Price, Quantity, Seller);
//do while loop start
do
{
//Ask user to enter product name and store it in appropriate local variable
System.out.print("Please Enter the Product Name: ");
Name = scan.next();
//Ask user to enter product price and store it in appropriate local variable
System.out.print("Please Enter the Price of the Product: ");
Price = scan.nextDouble();
//Ask user to enter quantity and store it in appropriate local variable
System.out.print("Please enter the Quantity: ");
Quantity = scan.nextInt();
//Ask user to enter product manufacturer name and store it in appropriate local variable
System.out.print("Please Enter the Manufacturer: ");
Seller = scan.next();
// create a new Product object using above inputed values
Product newitem = new Product(Name, Price, Quantity, Seller);
//add above created Product to the ArrayList cart if Product has available stock
// if stock not available inform user requested product is out of stock
//Ask user whether wants to continue shopping
//set the do while loop to continue to loop if Yes option is selected
} while (keepShopping.equals("Yes"));
// do while loop end
// header for shopping cart contents
// print details of each product added to the ArrayList
// calculate total price of the shopping cart
// print the total price of the shopping cart
}//end of main method
}//end of Shop class
And the Product class the professor provided:
//***************************************************************
//Product.java
//Represents an item in a shopping cart.
//***************************************************************
import java.text.NumberFormat;
public class Product
{
private String name;
private double price;
private int quantity;
private double subtotal;
private String manufacturer;
private int inventory;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Product (String name, double price, int quantity, String manufacturer)
{
this.name = name;
this.price = price;
this.quantity = quantity;
this.manufacturer = manufacturer;
subtotal = price*quantity;
inventory = 10;
}
public Product(String itemName, double itemPrice, int quantity2) {
// TODO Auto-generated constructor stub
}
// -------------------------------------------------------
// Return a string with the information about the Product
// -------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (manufacturer + " " + name + "\t\t " + fmt.format(price) + "\t " + quantity
+ "\t\t" + fmt.format(subtotal));
}
// Returns the unit price of the Product
public double getPrice()
{
return price;
}
// Returns the name of the Product
public String getName()
{
return name;
}
// Returns the quantity of the Product
public int getQuantity()
{
return quantity;
}
// Returns the sub total of the Product
public double getSubTotal()
{
return subtotal;
}
// Returns product manufacturer
public String getManufacturer()
{
return manufacturer;
}
// Checks whether product is in stock
// if after inventory get below stock after processing order, then
// places order to replenish stock
public boolean checkInventory()
{
boolean flag = false;
if (inventory > quantity)
{
flag = true;
inventory = inventory - quantity;
if (inventory <= 0)
placeOrder(quantity);
}
return flag;
}
// Replenishes stock to 10 times the quantity of last order
private void placeOrder(int orderQuantity)
{
inventory = orderQuantity * 10;
}
}//end of class Item
I would write a comment but for some reason its not giving me the option.
I don't understand the question? Do you just want me to do the assignment? What don't you understand?
It doesn't look like you're ever adding anything to the arrayList that you made. You created the product object but you need to add it to the list.....
Also it looks like you created a second constructor in your product class that I don't think you are using.