删除元素数组会导致NullPointerException

时间:2019-05-27 22:49:29

标签: java

我是Java的初学者。我必须做购物车。但是我坚持使用删除方法。

请帮助我!

我试图制作删除方法。但是效果不好。.

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

我想删除元素数组。但是输出是

Exception in thread "main" java.lang.NullPointerException

如果编译器运行良好,该怎么办。我认为删除方法是个问题。

2 个答案:

答案 0 :(得分:1)

NullPointerException可能是由此行if (cart[i].getTitle().equals(title))引起的,而不是访问cart对象本身,而是对来自{{1}的返回值调用equals方法}。在比较之前,请确保返回值不为空:

getTitle

无论如何,您都应该采用某种调试技术来确定到底是什么导致了您的错误。了解有关在Java中为Eclipse here和IntelliJ here进行调试的更多信息。

答案 1 :(得分:1)

出现java.lang.NullPointerException的原因是,您删除购物车中的第一项并将其设置为null,然后调用 shopCart.toString( )

因此,之前之前c1.getShopCart().removeItemFromCart("Harry Potter");,您拥有: 您购物车中的[“哈利·波特”,“艾比路”,“阿甘正传”],

之后 c1.getShopCart().removeItemFromCart("Harry Potter");,您有: [,“艾比路”,“阿甘正传”],您正在访问购物车[0]上的空指针。