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.
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.
I've already created the ticketAgent and ticketType class and I'm having a tough time trying to add the strings. I've tried using a wrapper class but not sure if that's even the right approach. I've pasted my code and then the prompt respectively. Thanks for the help. I'm a first time poster, so I hope I've followed the posting guidelines.
Prompt:
Write a program called TicketBooth that instantiates at 3 different ticket agents. The TicketBooth program should prompt the user for the ticket agent they wish to purchase a ticket from and then display the list of ticket types and prices that are available. The TicketBooth program should allow the user to make a selection for the ticket to purchase. After a ticket type is selected, the TicketBooth program should display the:
• total sales for that ticket agent
• total number of tickets sold by the ticket agent
• total number of tickets sold by all ticket agents
The TicketBooth program should continue to prompt the user to purchase tickets from one of the ticket agents until the user types quit.
package Exercises;
import java.util.Scanner;
public class TicketBooth {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
String ticketAgent = "sam", "nicole" , "alex";
String ticketType = "one";
int t = Integer.parseInt(ticketAgent);
int s = Integer.parseInt(ticketType);
int sum;
System.out.println("Please select your ticket agent: ");
ticketAgent = input.next();
System.out.println("Please select your ticket type or press -1 to quit: ");
ticketType = input.next();
sum = t +s;
System.out.println("The total tickets that were sold were: " + sum);
}
}
package exercises;
public class TicketAgent {
private static int numOfTicksPerAgent;
private String agentName;
private int numSold = 0;
private double totalSales = 0.0;
public TicketAgent(String agent) {
agentName = agent;
numSold = 0;
totalSales = 0.0;
numOfTicksPerAgent += 1;
}
public void sellTicket(TicketType tt) {
numSold++;
totalSales = totalSales + tt.getticketPrice();
numOfTicksPerAgent++;
}
public double gettotalSales() {
return totalSales;
}
public double getnumSold() {
return numSold;
}
public double getnumOfTicksPerAgent() {
return numOfTicksPerAgent;
}
}
package exercises;
public enum TicketType
{
CHILD (6.50),
ADULT (9.50),
SENIOR (6.50);
private double tikPrice;
TicketType(double price)
{
tikPrice = price;
}
public double getticketPrice()
{
return tikPrice;
}
}
The problem is, that it seems that this is your homework and
nobody wants to make your homeworks for you.
edit: I saw that you added your classes just now.
All you have to do is to add the do while loop
and instantiate your Agents in the right way.
Where, exactly, is your problem? So we can help you better.
My first approach would be, to make it simple,
to write a TicketAgent class and a TicketType class.
Write the TicketAgent in a way, you can put the name of
the agent and the types into the constructor.
TicketAgent agentSam = new TicketAgent("Sam", new ExpensiveTicket());
Add setter and getter methods.
And the TicketType needs a float value for the price and maybe a String description
or something like that.
After you are done with this, go back to your main class.
Open a do while loop and set as the loop argument a boolean
value for the user abort, which is false at the beginning and
changes if the user types in the quit command.
Before the loop, instantiate the Agents with the tickets.
Display names and prices. Display tickets. Count together. Ask for abort.
Hope this helps a little.
And sorry for my english, it is not my mother-tongue.
additional:
private boolean userWantsToQuit = false;
private List<TicketAgent> avaibleAgents = new ArrayList<TicketAgent>();
private List<TicketAgent> usedAgents= new ArrayList<TicketAgent>();
private List<TickeType> boughtTickets= new ArrayList<TicketType>();
main(...){
agents.add(new TicketAgent("Sam"));
agents.add(new TicketAgent("wise"));
agents.add(new TicketAgent("gamgee"));
do{
usedAgents.add(askUserForAgent()); //extra static method
boughtTickets.add(askUserForType(agent)); //extra static method
userWantsToQuit = askUserToQuit();//extra static method
}while(!userWantsToQuit);
displayAgentSummary(usedAgents);
displayTicketSummary(boughtTickets);
}
[...]
public static displayAgentSummary(List<TicketAgent> agents)
{
for(TicketAgent agent : agents)
{
System.out.println("Served by: " + agent.getName());
}
}
public static displayTicketSummary(List<TicketType> tickets)
{
float totalPrice = 0;
for(TicketType ticket : tickets)
{
totalPrice =+ ticket.getPrice();
System.out.println("You bought a " + ticket.getName() + " for " + ticket.getPrice()";
}
System.out.println("You bought tickets in total for " + totalPrice + " dollar".
}
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 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;