Why is my application throwing a NullPointerException? - java

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.

Related

constructor ItemToPurchase in class ItemToPurchase cannot be applied to given types;

Ive been looking through the forums but i cant seem to understand what exactly is my issue.
This is a classwork assignment and everything runs fine on my end. When i upload my code into zybook for submission it outputs are correct, but im getting errors with my set and get functions, under specific Unit tests.
"Tests item.setName("Chocolate Chips") and item.getName() == "Chocolate Chips"
Compilation failed
zyLabsUnitTest.java:5: error: constructor ItemToPurchase in class ItemToPurchase cannot be applied to given types;
ItemToPurchase item = new ItemToPurchase();
^
required: String,int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error"
I cannot change the private fields to public as the assignment states these must be private. Here is my code if anyone is kind enough to take a look
package onlineshoppingcart;
import java.util.*;
public class OnlineShoppingCart {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Item 1");
System.out.println("Enter the item name:");
String n;
n = kb.nextLine();
System.out.println("Enter the item price:");
int p;
p=kb.nextInt();
System.out.println("Enter the item quantity:");
int q;
q=kb.nextInt();
System.out.println();
ItemToPurchase item;
item = new ItemToPurchase(n, p, q);
//item.setName("Chcolate Chips");//testing to see if set & get are ==
//System.out.println(item.getName());//with my manual entry they are
item.setName(n);
item.setPrice(p);
item.setQuantity(q);
//fix me
//item.getName();
System.out.println("Item 2");
kb.nextLine();//to stop out scanner from skipping input
System.out.println("Enter the item name:");
n=kb.nextLine();
System.out.println("Enter the item price:");
p=kb.nextInt();
System.out.println("Enter the item quantity:");
q=kb.nextInt();
ItemToPurchase itemtwo;
itemtwo = new ItemToPurchase(n,p,q);
itemtwo.setName(n);
itemtwo.setPrice(p);
itemtwo.setQuantity(q);
System.out.println();
System.out.println("TOTAL COST");
System.out.println(item.getName()
+" "+ item.getQuantity()+" # $"
+item.getPrice()+" = $"
+item.getPrice()*item.getQuantity());
System.out.println(itemtwo.getName()
+" "+ itemtwo.getQuantity()+" # $"
+itemtwo.getPrice()+" = $"
+itemtwo.getPrice()*itemtwo.getQuantity());
System.out.println();
System.out.println("Total: $"+((
itemtwo.getPrice()*itemtwo.getQuantity())+(
item.getPrice()*item.getQuantity())));
}
}
package onlineshoppingcart;
public class ItemToPurchase {
private String itemName;
private int itemPrice;
private int itemQuantity;
private ItemToPurchase(){
String itemName = "null";
int itemPrice = 0;
int itemQuantity = 0;
}
ItemToPurchase(String n, int p, int q){
itemName = n;
itemPrice=p;
itemQuantity=q;
}
public void setName(String n){
itemName=n;
}
public void setPrice(int p){
itemPrice = p;
}
public void setQuantity(int q){
itemQuantity = q;
}
public String getName(){
return this.itemName;
}
public int getPrice(){
return this.itemPrice;
}
public int getQuantity(){
return this.itemQuantity;
}
}

Java Shopping Cart Array List (method addToCart not working) [duplicate]

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]
}

Binary Search method

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;
}
}

Shopping Cart Java Application (addToCart)

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;

Creating an Array from multiple user inputs of different types

How I would get the 3 items from user input Item (name, cost, priority) into one object item and place that object item into an array of other objects?
public class Main {
public static void main(String[] args) {
//here are my variables.
//I'm pretty sure a few of these should be defined
// in their own item class.
int i=0;
String name1;
int priority1;
double cost1;
//String[] shoppingList = new String[7];
String[] item = new String[7];
// I am able to grab input from the user for all 3 elements of
// an item object (name, cost, priority)
// I am missing how to save these 3 elements into an item object
// and create an array for each item object
for (i=0; i<item.length;i++) {
//I want to capture name, priority, and cost of each item
// and add each item as an in
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
"How I would get the 3 items from user input Item (name, cost, priority) into one object item"
If I understand you correctly, the solution would be to make a new class. Call it whatever is relevant for what you're doing
class Data {
String name;
double cost;
int priority;
Data(String name, double cost, int priority) { //Set variables }
}
Then you can create a new "Data" class with your relevant information with:
Data myObject = new Data("Input1", 37.50, 2);
Just for example, with random information. You can make as many of these unique objects as you'd like, and add them to an array or ArrayList depending on what you want to do:
Data[] myArray = new Data[100];
//or
List<Data> myList = new ArrayList<Data>();
You could try a custom class:
public class Item {
private String name;
private double price; // you should probably use an 'int' for this
// it would be the amount of cents
// that would avoid rounding errors
private int priority;
public Item(String name, double price, int priority) {
this.name = name;
this.price = price;
this.priority = priority;
}
// (getters and setters)
public String getName() {
return name;
}
...
}
Item milk = new Item("milk", 19.99, 3); // wow, expensive milk :P
Item[] items = [milk, new Item("cheese", 99.99, 2), ...];
What you could do is create a class, and use the constructor to help pass parameters. You could then make an instance of this class, and use it to set the parameters to whatever you need (i.e the name, price, etc.). Then accept the user input using the Scanner, and what I would do, is make an ArrayList of (I'll call it ItemData). Then, add the instance to the ArrayList using .add(this). Here's the code for each step:
Pass the parameters in the constructor:
public class ItemData{
public ItemData(String name, double cost, int priority){
}
}
Make a new instance of ItemData in the Main class at the end of the input:
ItemData itemData = new ItemData(name, cost, priority);
Make the ArrayList field (make sure you import java.util.ArrayList and java.util.List) :
List<ItemData> dataStorage = new ArrayList<ItemData>();
Add the instance of ItemData to the ArrayList into the ItemData constructor:
Main.(ArrayList name here).add(this);
Your final code should look like this:
public class ItemData{
public ItemData(String name, double cost, int priority){
Main.itemData.add(this);
}
}
import java.util.*;
public class Main {
public static List<ItemData> itemData = new ArrayList<ItemData>();
public static void main(String[] args) {
int i=0;
String name1;
int priority1;
double cost1;
String[] item = new String[7];
for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
ItemData x = new ItemData(name, cost, priority);
}
}
}
You should try making a User Defined Type which acts as a data structure to hold the values you desire.
Since java is an object oriented language, you can create a user defined type with a class. Below, I created a class called Item with three member data variables. This class is a blueprint for all Item type objects. Whenever you create a new item object, it will have its own unique copies of the member data variables.
For sake of simplicity, I did not encapsulate the member data variables, but for future programs you should declare member data variables private and provide an interface to access/modify them. Leaving them public here allows me the convenience of accessing them with the dot (.) operator.
See the following code for a working example
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Item {
public String name;
public int priority;
public double cost;
public static void main(String[] args) {
int itemAmount = 7;
List<Item> itemList = new ArrayList<Item>();
for (int i=0; i < itemAmount; i++) {
Item itemToCreate = new Item();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
itemToCreate.name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
itemToCreate.cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
itemToCreate.priority = keyboard3.nextInt();
itemList.add(itemToCreate);
} // end for
for (int i=0; i < itemList.size(); i++) {
Item tempItem = itemList.get(i);
System.out.println("Item " + tempItem.name + " has cost " + tempItem.cost + " with priority " + tempItem.priority);
}
} // end main
} // end class
You should notice I replaced your original declaration with an ArrayList data structure. This is a dynamic data structure that can grow as you insert items into it. You should take on the challenge of allowing for unlimited amount of user input and to account for an unknown quantity of Item objects in your list.
Hope this helps!
Your item class:
class Item {
String name;
double cost;
int priority;
Item(String name, double cost, int priority) {
this.name = name;
this.cost = cost;
this.priority = priority;
}
}
"An Array of objects" is a misnomer in Java, because arrays have fixed-length elements.
I do not think it's safe to assume all your Item objects will be the same size.
Use a "List" - or in Java, an "ArrayList"
ArrayList<Item> myCart = new ArrayList<Item>();
Create the item object:
Item myItem = new Item('cheese', 42.12, 1); //cheese is good
Append the item to the shopping cart:
myCart.add(myItem);
http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Creating an Arraylist of Objects

Categories