Results 1 to 12 of 12

Thread: Null Pointer

  1. #1
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Null Pointer

    This probably belongs in Java EE Servlets but wasn't positive, and this is my first attempt at Java so thought I'd start here.

    I have a servlet that is basically a shopping cart, you select some items on a website then it is supposed to display the name and price of the checked items and a total price. However when I press total, I get a null pointer exception error. It's probably a simple typo and I've been staring at this too long to see it, but I can't find the problem.

    You can download a zip of the files (from netbeans) at the link below. If there's a better/preffered way to post the code let me know and I can do that. tiger.towson.edu/~tbaldw2/tb08hw1.zip

  2. #2
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: Null Pointer

    post your code here buddy :)

  3. #3
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Null Pointer

    Ok, it's quite long which is why I didn't do that in the first place, and there's a few files involved, but I'll do that later tonight

  4. #4
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Null Pointer

    First is from the main program, Cart.java
    Java Code:
    package homework;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author Tenley 
     */
    public class Cart extends HttpServlet {
    
        /**
         * @param request
         * @param response
         * @throws javax.servlet.ServletException
         * @throws java.io.IOException
         */
        Item[] items = new Item[7];
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect("tb08hw1.html");
        } /*When the browser requests this page via the GET method, it will redirect the browser to the html page,
         * so it will always redirect to the html page unless called by another method like post (see below) */
    
    
        public void doDelete(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Requests a URI be remoted from the server
        public void doHead(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Same as get, but without the body, used for getting meta info from headers
        public void doOptions(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Gives the supported HTTP methods which can be used to test the functionality of a server
        public void doPut(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Used to update or change a resource
        public void doTrace(HttpServletRequest request,
                HttpServletResponse response) {
        }
        ;    
        //Received info is sent back so the requester can see if any changes have been made by the servers
        
        private static Map<Double, String> DRESSES = new HashMap<Double, String>();
    
        {
            DRESSES.put(149.99, "Alfred Angelo");
            DRESSES.put(149.00, "David&rsquo;s Bridal");
            DRESSES.put(159.99, "Jenny Woo");
            DRESSES.put(140.99, "Lela Rose");
            DRESSES.put(189.99, "Donna Morgan");
            DRESSES.put(139.00, "After Six");
            DRESSES.put(129.99, "Dessy");
        } // Initializing static elements, associates the label names with their values
    
        ; 
     //The doPost method below is called when the total button is selected on the website
     @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            String[] selected = request.getParameterValues("dress");
            StringBuilder sb = new StringBuilder(20);
            writeStrings(out, top);
            double[] totalArray = new double[7];
            //If no items are checked on the html file before hitting total:
            if (selected == null || selected.length == 0) {
                out.println(sb);
                out.println("Nothing checked");
                out.println("<p><a href=\"tb08hw1.html\">Go back and make a selection</a></p>");
                writeStrings(out, bottom);
            } else {
                out.println("<p>You selected</p>");
                for (int i = 0; i < items.length; i++) { //For loops runs once per item
                    if (items[i].isSelected() == true) { 
    //If an item is selected, this will output the name & price, and put the price into a new array
                        Item item = items[i];
                        sb.append("<table><tr><td>").append(item.getName()).append("</td>");
                        sb.append("<td>").append(item.getPrice()).append("</td></tr></table>");
                        totalArray[i] = item.getPrice();
                    } else {
                        continue;
                    }
                }
                double total = 0.0;
                for (int i = 0; i < totalArray.length; i++) {
                    total += totalArray[i] ;
                } //The price of all selected items was input in this array above. Added together to get the total here
                out.println("Your total is" + total);
                out.println("<p><a href=\"tb08hw1.html\">Go back and change your selection</a></p>");
            }
    
            writeStrings(out, bottom);
        }
    //Below is the HTML code that will be displayed when total is selected
        private static String[] top = {
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "<title>Checkout</title>",
            "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">",
            "</head>",
            "<body>",
            "<table>"};
        private static String[] bottom = {
            "</table",
            "</body>",
            "</html>"
        };
    
        //This allows the code above to be printed out easily
        private void writeStrings(PrintWriter out, String[] esses) {
            for (String s : esses) {
                out.println(s);
            }
        }
    }
    Last edited by me10lee83; 10-10-2013 at 07:36 PM.

  5. #5
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Null Pointer

    Here is the Class.java file
    Java Code:
    package homework;
    
    public class Item {
        private String description;
        private String name;
        private double price = 0.0;
        private boolean selected = false;
    
        public Item(String dressName, String dressDescription, double dressPrice, Boolean isSelected) {
            name = dressName;
            description = dressDescription;
            price = dressPrice;
            selected = isSelected;
        } 
    
        /**
         * @return the description
         */
        public String getDescription() {
            return description;
        }
    
        /**
         * @param descrption the description to set
         */
        public void setDescription(String description) {
            this.description = description;
        }
    
        /**
         * @return the name
         */
        public String getName() {
            return name;
        }
    
        /**
         * @param name the name to set
         */
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * @return the price
         */
        public double getPrice() {
            return price;
        }
    
        /**
         * @param price the price to set
         */
        public void setPrice(double price) {
            this.price = price;
        }
    
        /**
         * @return the selected
         */
        public boolean isSelected() {
            return selected;
        }
    
        /**
         * @param selected the selected to set
         */
        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

  6. #6
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Null Pointer

    And here is the website

    XML Code:
    <!DOCTYPE html>
    
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>AIT 618 Homework 1</title>
    </head>
    
    <body>
        <h1 style="text-align:center">Bridesmaid Dresses</h1>
    
        <form action="tb08hw1" method="POST"> 
            <table style="border-style:solid; border-width:1px; border-collapse:collapse">
                <tr>
                    <th></th>
                    <th>Name</th>
                    <th>Description</th>
                    <th>Price</th>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="dress" value=149.99/></td>
                    <td style="border-style:solid; border-width:1px">Alfred Angelo</label> Pleated Strapless Dress</td>
                    <td style="border-style:solid; border-width:1px">Who says you can&rsquo;t wear a bridesmaid dress again? This dress hugs your curves in all the right places to give a slimming look. The strapless sweetheart neckline is elegant and perfect for any bridesmaid. This tea length dress is fully lined dress, back zip, and dry clean only and is available in sizes 2 - 20W and comes in all 20 colors.</td>
                    <td style="border-style:solid; border-width:1px">$149.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="dress" value=149.00/></td>
                    <td style="border-style:solid; border-width:1px">David&rsquo;s Bridal</label> Sleeveless Chiffon Dress</td>
                    <td style="border-style:solid; border-width:1px">A "must have" for your bridal party. This dress has a high neckline with beaded straps and a keyhole detail. Made from tafeta, this dress features an elastic waist to help flatter any figure. Designed at knee length it is fully lined with a back zip. This dress is available in canary, clover, malibu, and plum and is available in sizes 0 - 30W.</td>
                    <td style="border-style:solid; border-width:1px">$149.00</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="dress" value=159.99/></td>
                    <td style="border-style:solid; border-width:1px">Jenny Woo</label> Organza Strapless Dress</td>
                    <td style="border-style:solid; border-width:1px">A whimsical and charming look that your bridesmaids will love. This dress is breathtaking with the addition of pick-up points at the skirt. Made from organza, it has optional spaghetti straps to make everyone comfortable. This dress is available in all 20 colors and sizes 2 to 20W and 8JB to 16JB.</td>
                    <td style="border-style:solid; border-width:1px">$159.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="dress" value=140.99/></td>
                    <td style="border-style:solid; border-width:1px">Lela Rose</label> Chiffon Strappless Dress with Cap Sleeves</td>
                    <td style="border-style:solid; border-width:1px">This ravishing dress features a sweetheart neckline with cap sleeves. Available in floor length or tea length, it includes a rhinestone flower waistband. It is available in wheat, silver mist, copper, sunset, and guava in sizes 0 to 20W and maternity sizes.</td>
                    <td style="border-style:solid; border-width:1px">$140.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="dress" value=189.99/></td>
                    <td style="border-style:solid; border-width:1px">Donna Morgan</label> Strapless Satin Ballgown</td>
                    <td style="border-style:solid; border-width:1px">Take a step into the old world with the satin ballgown style dress. The illusion neckline and flowered waistband add a unique twist to this dress that everyone will love. Available in dark pacific, cameo, bermuda blue, and carnation and sizes sizes 0 to 30W and 8JB to 16JB.</td>
                    <td style="border-style:solid; border-width:1px">$188.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="dress" value=139.00/></td>
                    <td style="border-style:solid; border-width:1px">After Six</label> Cocktail Length with Ruched Waist</td>
                    <td style="border-style:solid; border-width:1px">Your girls will sweep down the aisle in this sleek gown. Made of soft net with with a grosgrain ribbon sash the one-shoulder dress is availabe in sizes 0 to 30W and all 15 soft net colors.</td>
                    <td style="border-style:solid; border-width:1px">$139.00</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="dress" value=129.99/></td>
                    <td style="border-style:solid; border-width:1px">Dessy</label> Bobbin Net Dress with Rounded Neckline</td>
                    <td style="border-style:solid; border-width:1px">Vintage-inspired, the cocktail length dress has an asymetrically draped bubble skirt. Straps adorned with crystal beading, rhinestones, and sequins make this dress one of a kind. This dress is available in all 50 dream in color shades and sizes 0 to 30W and 8JB to 14JB</td>
                    <td style="border-style:solid; border-width:1px">$129.99</td>
                </tr>
            </table>
            <input type="submit" name="Total" value="Total">
        </form>
    </body>
    </html>

  7. #7
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: Null Pointer

    what line is the error on?

  8. #8
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Null Pointer

    Thank you, I didn't realize it mentioned the line number in the error. That helped, but still not sure how to accomplish what I'm trying to do.

    The error is line 95 of Class.java, seems to be an issue with the if statement "if (items[i].isSelected() == true)" If that doesn't work, how else can I get it to perform lines 97 - 100 only if an item is selected?

  9. #9
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default Re: Null Pointer

    When people get a NPE with an array of objects it usually because they try to use an object in the array before they have created them.
    Java Code:
    String[] words = new String[10];
    System.out.println(words[0].length()); // NPE
    What is the String in the array? There isn't one.

  10. #10
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Null Pointer

    Maybe I'm misunderstanding, but line 95 doesn't use a string, isSelected returns a boolean value in Items.class
    The array is initialized to the items class, Item[] items = new Item[7]; in line 23 and Item item = items[i]; in line 97.
    I am using Netbeans, which usually gives an error if something hasn't been created, initialized, etc properly and it's not showing any errors.

  11. #11
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default Re: Null Pointer

    Java Code:
    Item[] items = new Item[7];
    Yes that line of code creates the array but that is all it does. It DOES NOT create the objects in the array. You have to do that.

  12. #12
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Null Pointer

    Thank you, I didn't realize I wasn't using the map at all, so the form data wasn't being put into the array. I corrected that (new code below), and no longer get a NullPointerException, however it's not working properly. It does not output the name and price of the selected items, and it's not adding the values. It just says:
    You Selected
    Your total is $0.0

    Part of the issue I think is line 101 "String dress = DRESSES.get(buy);" Netbeans is giving a warning, "Given object cannot contain instances of String (expected Double)" and line 82 "String[] selected = request.getParameterValues("buy");". How do I request the double values? Also, the map data is not being added to the Items array I don't think which is prob at least part of the issue as well. How do I accomplish this, or just iterate through the array and not use the Items.class if that would be easier.

    Java Code:
    package homework;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author Tenley Baldwin
     */
    public class Cart extends HttpServlet {
    
        /**
         * @param request
         * @param response
         * @throws javax.servlet.ServletException
         * @throws java.io.IOException
         */
        Item[] items = new Item[7];
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect("tb08hw1.html");
        } /*When the browser requests this page via the GET method, it will redirect the browser to the html page,
         * so it will always redirect to the html page unless called by another method like post (see below) */
    
    
        public void doDelete(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Requests a URI be remoted from the server
        public void doHead(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Same as get, but without the body, used for getting meta info from headers
        public void doOptions(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Gives the supported HTTP methods which can be used to test the functionality of a server
        public void doPut(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Used to update or change a resource
        public void doTrace(HttpServletRequest request,
                HttpServletResponse response) {
        }
        ;    
        //Received info is sent back so the requester can see if any changes have been made by the servers
        
        private static Map<Double, String> DRESSES = new HashMap<Double, String>();
    
        {
            DRESSES.put(149.99, "Alfred Angelo");
            DRESSES.put(149.00, "David&rsquo;s Bridal");
            DRESSES.put(159.99, "Jenny Woo");
            DRESSES.put(140.99, "Lela Rose");
            DRESSES.put(189.99, "Donna Morgan");
            DRESSES.put(139.00, "After Six");
            DRESSES.put(129.99, "Dessy");
        } // Initializing static elements, associates the label names with their values
    
        ; 
     //The doPost method below is called when the total button is selected on the website
     @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            String[] selected = request.getParameterValues("buy");
            StringBuilder sb = new StringBuilder(20);
            writeStrings(out, top);
            double[] totalArray = new double[7];
            
            //If no items are checked on the html file before hitting total:
            if (selected == null || selected.length == 0) {
                out.println(sb);
                out.println("Nothing selected");
                out.println("<p><a href=\"tb08hw1.html\">Go back and make a selection</a></p>");
                writeStrings(out, bottom);
            } else {
                out.println("<p>You selected</p>");
                out.println("<table>");
                for (String buy : selected) {
                    //for (int i = 0; i < items.length; i++) { //For loops runs once per item
                    if (buy == null || buy.isEmpty()) {
                        continue;
                    }
                    String dress = DRESSES.get(buy);
                    int i = 0;
                    if (dress != null && !dress.isEmpty()) {
                        //if (items[i].isSelected() == true) { 
                        Item item = items[i];
                        sb.append("<tr><td>").append(item.getName()).append("</td>");
                        sb.append("<td>").append(item.getPrice()).append("</td></tr>");
                        totalArray[i] = item.getPrice();
                    } else {
                        continue;
                    }
                }
                double total = 0.0;
                for (int i = 0; i < totalArray.length; i++) {
                    total += totalArray[i];
                } //The price of all selected items was input in this array above. Added together to get the total here
                out.println("</table>");
                out.println("Your total is $" + total);
                out.println("<p><a href=\"tb08hw1.html\">Go back and change your selection</a></p>");
            }
    
            writeStrings(out, bottom);
        }
    //Below is the HTML code that will be displayed when total is selected
        private static String[] top = {
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "<title>Checkout</title>",
            "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">",
            "</head>",
            "<body>",
            "<table>"};
        private static String[] bottom = {
            "</table",
            "</body>",
            "</html>"
        };
    
        //This allows the code above to be printed out easily
        private void writeStrings(PrintWriter out, String[] esses) {
            for (String s : esses) {
                out.println(s);
            }
        }
    }
    Last edited by me10lee83; 10-11-2013 at 02:49 PM.

Similar Threads

  1. Null pointer
    By WSUVanc in forum New To Java
    Replies: 5
    Last Post: 03-15-2013, 02:19 AM
  2. Null pointer exception
    By jessie in forum New To Java
    Replies: 5
    Last Post: 02-08-2011, 02:58 PM
  3. Null Pointer
    By theen3my in forum AWT / Swing
    Replies: 3
    Last Post: 10-03-2009, 02:10 PM
  4. Null pointer exception
    By talha06 in forum JDBC
    Replies: 5
    Last Post: 07-14-2009, 01:12 AM
  5. null pointer help
    By mayhewj7 in forum New To Java
    Replies: 5
    Last Post: 02-17-2009, 11:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •