Chat LIVE With Programming Experts! There Are 23 Online Right Now...

Welcome to Dream.In.Code
Become a Java Expert!

Join 244,305 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 791 people online right now. Registration is fast and FREE... Join Now!




Help with Null Pointer Exception and sort code

 
Reply to this topicStart new topic

Help with Null Pointer Exception and sort code

shanesing77
26 Nov, 2008 - 06:06 AM
Post #1

New D.I.C Head
*

Joined: 24 Oct, 2008
Posts: 15

I posted this a couple of days ago, but I still need help. I tried to fix the null pointer error, but have not been successful. I am getting:
Exception in thread "main" java.lang.NullPointerException
at testproduct.Product.getTotalInvValue(Product.java:40)
at testproduct.Product.printInventory(Product.java:53)
at testproduct.TestProduct.main(TestProduct.java:57)

I think it has to do with the way my getTotalInvValue method is written. Also, I have a method for sorting, but I do not know how to write the code in my TestProduct application. I have tried several codes like items.itemsort();, but it keeps saying that method can not be found. Please help!

CODE


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package testproduct;


import javax.swing.JOptionPane;

/**
*
* @author shannon.singleton
*/
public class Product
{
    
    int inventorySize = 15;
    protected Product items[] = new Product[inventorySize];
    
   public void addProduct(Product item) {
        for (int i = 0; i < inventorySize; i++) {
            if (items[i] == null) {
                items[i] = item;
                return;
            }
        }
    }
public double getTotalInvValue()
{
        double sumOfInventory = 0;
        for (Product item : items)
    {
            
     sumOfInventory += item.getProductValue();
    
     }
     return sumOfInventory;
}
public void printInventory()
{
    for (Product item : items)
    {
        String str = item.toString() + "     Item Number:" + item.getItemNum();
        str += " Units In Stock:" + item.getUnitsInStock();
        str += "     Value:" + item.getProductValue() + "\nThe total DVD inventory collection is: " + item.getTotalInvValue();  //

JOptionPane.showMessageDialog(null, str, "Title",  JOptionPane.PLAIN_MESSAGE);

    
    }
}

    protected String productName;
    protected int itemNum;
    protected int unitsInStock;
    protected double unitPrice;
    
    public Product(String dvd, int number, int stock, double price)
    {
        productName = dvd;
        itemNum = number;
        unitsInStock = stock;
        unitPrice = price;
    }
    
    public Product()
    {
        productName = " ";  
        itemNum = 0;
        unitsInStock = 0;
        unitPrice = 0;
     }
    
    // String representation of the product
    
    @Override
    public String toString()
    {
        return productName + "     Price:" + unitPrice;
    }

    public double getProductValue()
    {  
            return (double) unitsInStock * unitPrice;  
    }  
      
    public String getproductName()
    {
        return productName;
    }

    public void setProductName(String strProductName)  
    {  
       productName = strProductName;  
    }  
  
    public void setUnitPrice(double strUnitPrice)
    {
        unitPrice = strUnitPrice;
    }
    
    public double getUnitPrice()
    {
        return unitPrice;//retrieves unit price
    }
    
    public void setUnitsInStock(int strUnitsInStock)
    {
        unitsInStock = strUnitsInStock;//sets product name
    }
    
    public int getUnitsInStock()
    {
        return unitsInStock;//retrieves units in stock
    }
    
    public void setItemNum(int strItemNum)
    {
        itemNum = strItemNum;//sets product name
    }
    public int getItemNum()
    {
        return itemNum;//retrieves item number
    }
    
    public static void sortItems(Product items[])
    {
        String test, itemName;
        Product prodTemp;
        
        for(int i=0; i<items.length; i++)
        {
            test = items[i].toString();
            
            for(int j=i; j<items.length; j++)
            {
                itemName = items[j].toString();
                if (itemName.compareToIgnoreCase(test) < 0)
                {
                    prodTemp = items[i];
                    items[i] = items[j];
                    items[j] = prodTemp;
                                        
                }
            }
            
        }
      
    }
}



CODE

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package testproduct;

/**
*
* @author shannon.singleton
*/
public class Subclass extends Product
{
    
    protected String movieActor;
    
  public Subclass(String productName, int itemNum, int unitsInStock, double unitPrice, String actor)
    {
        // Pass on the values needed for creating the Product class
        super(productName, itemNum, unitsInStock, unitPrice);
        movieActor = actor;
    }
  
  public Subclass()
    
    {
        productName = " ";  
        itemNum = 0;
        unitsInStock = 0;
        unitPrice = 0;
        movieActor = " ";
     }

    public void setActor(String strMovieActor)
    {
        movieActor = strMovieActor;
    }

    public String getActor()
    {
        return movieActor;
    }

    @Override
public double getProductValue()
    {
        return super.getProductValue() * 1.05;
    }

        public double getRestockingFee()
    {
        return super.getProductValue() * .05;
    }

    @Override
public String toString()
    {
           return super.toString() + "     Actor:" + movieActor;
    }
}



CODE

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package testproduct;


/**
*
* @author shannon.singleton
*/
public class TestProduct {

    /**
     * @param args the command line arguments
     */
     public static void main(String[] arg)
  
    {
        Subclass item1 = new Subclass("Indiana Jones", 23457, 12, 14.99, "Harrison Ford");//assigns values to items

        Subclass item2 = new Subclass("The Hulk", 67842, 17, 14.99, "Edward Norton"); //assigns values to items

        Subclass item3 = new Subclass("Iron Man", 77089, 10, 14.99, "Robert Downey JR."); //assigns values items

        Subclass item4 = new Subclass("Spiderman 3", 22547, 8, 10.99, "Tobey Maguire"); //assigns values to items

        Subclass item5 = new Subclass ("Superman Returns", 40439, 11, 11.99, "Brandon Routh");//assigns values to items

        Subclass item6 = new Subclass("Spiderwick Chronicles", 50459, 9, 12.99, "Freddie Highmore"); //assigns values to items

        Subclass item7 = new Subclass ("Kung Fu Panda", 47865, 14, 17.99, "Jack Black"); //assigns values to items

        Subclass item8 = new Subclass ("Speed Racer", 23969, 6, 15.99, "Emile Hirsch");//assigns values to items

        Subclass item9 = new Subclass ("Get Smart", 60571, 18, 19.99, "Steve Carrell"); //assigns values to items

        Subclass item10 = new Subclass ("Batman The Dark Knight", 18590, 19, 19.99,"Christian Bale");//assigns values to items

        Subclass items = new Subclass();//creates object items

        items.addProduct(item1);
        items.addProduct(item2);
        items.addProduct(item3);
        items.addProduct(item4);
        items.addProduct(item5);
        items.addProduct(item6);
        items.addProduct(item7);
        items.addProduct(item8);
        items.addProduct(item9);
        items.addProduct(item10);
        
  
  items.printInventory();//prints inventory list
  
  System.out.println();
  
  }

}


User is offlineProfile CardPM
+Quote Post


Martyr2
RE: Help With Null Pointer Exception And Sort Code
26 Nov, 2008 - 11:18 AM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 6,656



Thanked: 613 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Well the main issue there with the nullpointer is because you have a for each loop which is going to iterate through all 15 items of your array, whether or not there is an actual product stored there. So the first time it hits a null value it is going to fail. So what you need to do is simply check if the value in the next slot of the array is actually a stored product or not.

java

public double getTotalInvValue()
{
double sumOfInventory = 0;
for (Product item : items)
{
// Here we check to make sure there is an actual item in this spot of the array.
// If there is, then call its getProductValue() and add it to the sum.
// Otherwise we are going to skip over it.
if (item != null) { sumOfInventory += item.getProductValue(); }

}
return sumOfInventory;
}


So once we put this check in place to make sure that there is an actual item in that part of the array, we can then call its getProductValue() function and add it to the sum.

This will resolve your NullPointerException.

Let us know if there is anything else we can help you with.

"At DIC we are nullpointerexception handling code ninjas... we are willing to give pointers on anything... dating, love, how to make a good martini... anything." decap.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 7/4/09 06:31PM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month