I'm a beginner in Java. I have to make shopping cart. But I'm stuck on remove method.
Please help me!
I tried to make remove method. But it doesn't work well..
Customer.java
public class Customer {
private String id;
private String firstName;
private String lastName;
private ShoppingCart shopCart;
public Customer(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
shopCart = new ShoppingCart();
}
public ShoppingCart getShopCart() {
return this.shopCart;
}
@Override
public String toString() {
return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
+ this.firstName + " " + this.lastName + "\n\n"
+ "Shopping list: \n\n" + shopCart.toString());
}
ShoppingCart.java
public class ShoppingCart {
private int itemCount;
private double totalPrice;
private static int capacity;
private Item[] cart;
public ShoppingCart()
{
capacity = 5;
itemCount = 0;
totalPrice = 0.0;
cart = new Item[capacity];
}
public void addBooktoCart(String title, String description, double price, int pageCount) {
if (itemCount < 5) {
Item item = new Book(title, description, price, pageCount);
totalPrice += price;
cart[itemCount] = item;
itemCount += 1;
}
else {
System.out.println("The maximum number that you can input is 5." +
"You cannot add item anymore");
}
}
//This remove method may be a problem.
public void removeItemFromCart(String title) {
boolean found = false;
for (int i = 0; i < cart.length; i++) {
if (cart[i] != null)
{
if (cart[i].getTitle().equals(title)) {
totalPrice -= cart[i].getPrice();
cart[i] = null;
itemCount -= 1;
found = true;
}
}
}
if(found != true) {
System.out.println("Item is not found in cart. Nothing removed");
}
}
@Override
public String toString() {
String contents = "";
for (int i = 0; i < itemCount; i++)
{
contents += cart[i].toString() + "\n\n";
}
String strDouble = String.format("%.2f", totalPrice);
contents += "The total price is: $" + strDouble + "\n\n"
+ "How many items do you have in your shopping cart? \n"
+ "There are " + this.itemCount + " items in my shopping cart. "+ "\n";
return contents;
}
}
Test.java
public class Test {
public static void main(String[] args) {
Customer c1 = new Customer("12345", "Hyun Min", "Lim");
c1.getShopCart().addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);
c1.getShopCart().addCDtoCart("Abbey Road", "Pop Genre", 6.50, 18);
c1.getShopCart().addMovietoCart("Forrest Gump", "Drama Genre", 13.23, 141);
c1.getShopCart().removeItemFromCart("Harry Potter");
System.out.println(c1.toString());
}
I want to remove array of elements. But output is
Exception in thread "main" java.lang.NullPointerException
.
What do I do if the compiler works well. I think that the remove method is a problem.