-1

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.

Sudhir Ojha
  • 3,009
  • 2
  • 11
  • 23
Hm L
  • 29
  • 4
  • 1
    I don't believe stackoverflow is here to solve you homework. But anyway you can start by looking at the stacktrace and backtrack to where the null pointer actually is, and after that decide why that is happening – João Costa May 27 '19 at 22:57
  • 1
    I wholeheartedly agree with the comment above, you should try to put more effort in debugging your code before asking for help. If you are unfamiliar with debugging in general check my answer for more details. – Matthew May 27 '19 at 23:11
  • @JoãoCosta Thank you for replying my question. But there is type of question that I can choose. And I chose that I need help with a homework problem. So I think that it doesn't matter that I ask about homework problem by using stackoverflow. Why not? And Sorry I don't know stacktrace and backtrack. – Hm L May 27 '19 at 23:16
  • @Matthew Ah.. Ok. But I've been trying to solve this problem for 4 hours.. So that's why I ask it.. – Hm L May 27 '19 at 23:19
  • 1
    It's not about stackoverflow in particular but the way you posted your question. In my opinion the question would be better off if you asked how to debug this current problem instead of how to resolve a `NullPointerException`, to which the answer is always the same: *figure out what part of the code is causing it with debugging.* – Matthew May 27 '19 at 23:25
  • In any case read my answer for more information about what might be causing the exception to occur, and if that resolves your problem please accept the answer and if not provide more information about your further issues. – Matthew May 27 '19 at 23:26
  • 1
    @Matthew Ah.. Ok. Thank you! Actually, I know why NullPointerException is caused, which is that I should not access getTitle() if cart[i] is null. But I don't know how to change my code.. This is really what I want to ask about. Yeah.. You're right. I agree. Sorry, You know that I've not written much the question by using stackoverflow. I should've written the question more specific. Thank you for your advice. I'll do it next time. Your answer is helpful for me! Thank you. – Hm L May 27 '19 at 23:42
  • @HmL stacktrace are the lines near where you got the "Exception in thread "main" java.lang.NullPointerException." if you read the first few lines you will eventually find the name of the class where the problem was, and even the line number! :) – João Costa May 28 '19 at 08:22
  • By backtrack (nothing technical). I mean starting from one place and retracing the steps that made you get to an error where there were none before. – João Costa May 28 '19 at 08:24

2 Answers2

1

The NullPointerException is probably caused by this line if (cart[i].getTitle().equals(title)) and not by accessing the cart object itself but invoking the equals method on a return value from getTitle. Check to make sure that the return value is not null before you compare it:

if (cart[i] != null)
{
    /* Assign the value to a local variable and then
     * check if it's null before accessing it.
     */
    String value = cart[i].getTitle();
    if (value != null && value.equals(title)) {
        totalPrice -= cart[i].getPrice();
        cart[i] = null;
        itemCount -= 1;
        found = true;
    }
}

In any case you should be employing some kind of debugging technique to determine what exactly is causing your errors. Find out more about debugging in Java for Eclipse here and for IntelliJ here.

Matthew
  • 1,779
  • 3
  • 15
  • 23
1

The java.lang.NullPointerException appears because you delete and set the first item in your cart to null, and than when you try to access it in your toString method from Customer.java when you call shopCart.toString().

So, before c1.getShopCart().removeItemFromCart("Harry Potter"); you have : ["Harry Potter", "Abbey Road", "Forrest Gump"] in your cart,

after c1.getShopCart().removeItemFromCart("Harry Potter"); you have: [null, "Abbey Road", "Forrest Gump"] and you are accessing the null pointer at cart[0].