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;
}
}
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]
}
My code is running fine at the beginning, but in the while loop, it won't prompt the user for the next input, and is just responding with no such element exception. I have tried fixing it for at least an hour, and have had no luck. Any tips on what might be wrong with it?
public class Inventory {
public static void main(String[] args) {
Store store = new Store();
String itemName;
System.out.println("Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item.");
boolean condition = true;
Scanner s = new Scanner(System.in);
do{
System.out.println("Please select an option and type the option number." + "\n 0. Quit \n 1. Add an item \n 2. Display stock for an item \n 3. Discontinue an item");
String choice = s.next();
if(choice.equals("0")){
System.out.println("Thank you for using the Sports Inventory Application. Good bye.");
condition = false;
System.exit(0);
}
else if(choice.equals("1")){
store.addItem();
}
else if(choice.equals("2")){
System.out.println("Item Name: ");
itemName = s.nextLine();
store.displayItem(itemName);
}
else if(choice.equals("3")){
System.out.println("Item Name: ");
itemName = s.nextLine();
store.deleteItem(itemName);
}
}
while(condition == true);
}
}
results in:
Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item.
Please select an option and type the option number.
0. Quit
1. Add an item
2. Display stock for an item
3. Discontinue an item
1
Item Name:
test
Item Amount:
120
Item added. Information: test
Current amount in inventory is: 120
Please select an option and type the option number.
0. Quit
1. Add an item
2. Display stock for an item
3. Discontinue an item
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Inventory.main(Inventory.java:24)
EDIT: Here are the other classes of the program:
import java.util.ArrayList;
import java.util.Scanner;
public class Store {
private ArrayList<Item> inventory;
public Store(){
inventory = new ArrayList<Item>();
}
public void addItem(){
Item newItem;
int itemAmount;
String itemName;
Scanner input = new Scanner(System.in);
System.out.println("Item Name: ");
itemName = input.nextLine();
System.out.println("Item Amount: ");
itemAmount = input.nextInt();
newItem = new Item(itemName, itemAmount);
inventory.add(newItem);
System.out.println("Item added. Information: " + inventory.get(0));
input.close();
}
public void deleteItem(String itemName){
int itemIndex;
Item itemToDelete;
itemToDelete = new Item(itemName);
itemIndex = inventory.indexOf(itemToDelete);
if(itemIndex > -1){
inventory.remove(itemIndex);
}
else{
System.out.println("Item does not exist.");
}
}
public void displayItem(String itemName){
int itemIndex;
Item itemToDisplay, item;
itemToDisplay = new Item(itemName);
itemIndex = inventory.indexOf(itemToDisplay);
if (itemIndex > -1){
item = inventory.get(itemIndex);
System.out.println(item);
}
else{
System.out.println("Item does not exist.");
}
}
}
Item Class:
public class Item {
private int itemAmount;
private String itemName;
public Item(String name, int amount){
this.itemName = name;
this.itemAmount = amount;
}
public Item(String name){
itemAmount = 0;
this.itemName = name;
}
public int getItemAmount(){
return itemAmount;
}
public String getItemName(){
return itemName;
}
public String getItem(){
return itemName + itemAmount;
}
#Override
public String toString(){
String itemString;
itemString = this.itemName + "\n";
itemString += "Current amount in inventory is: " + this.itemAmount;
return itemString;
}
}
You are calling Scanner.next() without first calling Scanner.hasNext().
Scanner.next is throwing the exception because it's reached the end of file. You should end your loop when Scanner.hasNext() returns false (check at the start using a while loop.)
EDIT:
You have closed a locally-declared Scanner in method addItem(). That has the side-effect of closing the backing channel, i.e. standard input. Therefore, the scanner in your main loop can no longer get any more input - it sees a closed file.
Although it's good general advice to close whatever you open in the same method, in the case of standard input you should only ever close that your application exits.
It seems to be a problem with your code using multiple Scanner objects,
try to define a single Scanner instance and then use it all over the code (check this answer for more details: How to use multiple Scanner objects on System.in?).
Also, you missed the equals and hashCode overriding for the Item class, mandatory when calling indexOf if you want the correct object to be retrieved:
So I will post here a version that is working fine for me:
Store class:
public class Store {
private ArrayList<Item> inventory;
public Store(){
inventory = new ArrayList<>();
}
public void addItem(Scanner input){
Item newItem;
int itemAmount;
String itemName;
System.out.println("Item Name: ");
itemName = input.nextLine();
System.out.println("Item Amount: ");
itemAmount = Integer.parseInt(input.nextLine());
newItem = new Item(itemName, itemAmount);
inventory.add(newItem);
System.out.println("Item added. Information: " + inventory.get(0));
}
public void deleteItem(String itemName){
int itemIndex;
Item itemToDelete;
itemToDelete = new Item(itemName);
itemIndex = inventory.indexOf(itemToDelete);
if(itemIndex > -1){
inventory.remove(itemIndex);
}
else{
System.out.println("Item does not exist.");
}
}
public void displayItem(String itemName){
int itemIndex;
Item itemToDisplay, item;
itemToDisplay = new Item(itemName);
itemIndex = inventory.indexOf(itemToDisplay);
if (itemIndex > -1){
item = inventory.get(itemIndex);
System.out.println(item);
}
else{
System.out.println("Item does not exist.");
}
}
}
Item class:
public class Item {
private int itemAmount;
private String itemName;
public Item(String name, int amount){
this.itemName = name;
this.itemAmount = amount;
}
public Item(String name){
itemAmount = 0;
this.itemName = name;
}
public int getItemAmount(){
return itemAmount;
}
public String getItemName(){
return itemName;
}
public String getItem(){
return itemName + itemAmount;
}
#Override
public String toString(){
String itemString;
itemString = this.itemName + "\n";
itemString += "Current amount in inventory is: " + this.itemAmount;
return itemString;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Item)) return false;
Item item = (Item) o;
return itemName.equals(item.itemName);
}
#Override
public int hashCode() {
return itemName.hashCode();
}
Inventory class:
public class Inventory {
public static void main(String[] args) {
Store store = new Store();
String itemName;
System.out.println("Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item.");
boolean condition = true;
Scanner s = new Scanner(System.in);
do {
System.out.println("Please select an option and type the option number." + "\n 0. Quit \n 1. Add an item \n 2. Display stock for an item \n 3. Discontinue an item");
String choice = s.nextLine();
if (choice.equals("0")) {
System.out.println("Thank you for using the Sports Inventory Application. Good bye.");
condition = false;
System.exit(0);
} else if (choice.equals("1")) {
store.addItem(s);
} else if (choice.equals("2")) {
System.out.println("Item Name: ");
itemName = s.nextLine();
store.displayItem(itemName);
} else if (choice.equals("3")) {
System.out.println("Item Name: ");
itemName = s.nextLine();
store.deleteItem(itemName);
}
}
while (condition == true);
}
}
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 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;
I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}