Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Using an If statement to check boxes

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Using an If statement to check boxes

    I have a servlet that is basically a shopping cart. You select some items, POST is called and it totals them up and gives the total of selected items. When the back button is clicked (which really just reloads the servlet via GET) I want it to remember what was checked. I have created a map of checked items, but can't figure out how to get it to read if there is data in the getName field. The if statement I'm trying is giving an illegal start of expression error.

    package homework;
     
    import java.text.DecimalFormat;
    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]; //Creating an array for the items class
        Map<String, Item> itemMap = new HashMap<String, Item>(19);
     
        @Override //Filling the items class with the items
        public void init() {
            items[0] = new Item("Alfred Angelo Pleated Strapless Dress", "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.", 149.99, false);
            items[1] = new Item("Davids Bridal Sleeveless Chiffon Dress", "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.", 149.0, false);
            items[2] = new Item("Jenny Woo Organza Strapless Dress", "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.", 159.99, false);
            items[3] = new Item("Lela Rose Chiffon Strapless Dress with Cap Sleeves", "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.", 140.99, false);
            items[4] = new Item("Donna Morgan Strapless Satin Ballgown", "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.", 188.99, false);
            items[5] = new Item("After Six Cocktail Length with Ruched Waist", "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.", 139.0, false);
            items[6] = new Item("Dessy Bobbin Net Dress with Rounded Neckline", "Vintage-inspired, the cocktail length dress has an asymmetrically 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", 129.99, false);
            for (Item item : items) {
                itemMap.put(item.getName(), item);
            }
        }
     
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            StringBuilder sb = new StringBuilder(20);
            Map<String, Item> checkedItems = new HashMap<String, Item>(19);
     
            writeStrings(out, top); //Printing the HTML headers
            writeStrings(out, middle); //Start of the table & page title
     
            for (int i = 0; i < items.length; i++) { 
                Item item = items[i];
                sb.append("<tr><td style='border-style:solid; border-width:1px'><label><input type='checkbox' name='buy' value='").append(items[i].getName());
                if (checkedItems.get(item.getName())!=null)) {
                    sb.append("checked");
                }
                sb.append("'/></label></td>");
                sb.append("<td style='border-style:solid; border-width:1px'>").append(item.getName()).append("</td>");
                sb.append("<td style='border-style:solid; border-width:1px'>").append(item.getDescription()).append("</td>");
                sb.append("<td style='border-style:solid; border-width:1px'>$").append(item.getPrice()).append("</td>");
            }
            out.println(sb + "</tr></table>"); 
            writeStrings(out, formEnd); 
            writeStrings(out, bottom); 
        }
     
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException { //This is run when the POST method is called, when the form is submitted
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String[] selected = request.getParameterValues("buy"); //reads in the values of the dress form
            String[] tax = request.getParameterValues("md"); //reads in whether tax is selected
            DecimalFormat df = new DecimalFormat("0.00##"); //When DecimalFormat is called, the number is rounded to two decimal places
     
            double total = 0.0;
            double[] prices = new double[7]; //Creating an array to store the dress prices in
            Map<String, Item> checkedItems = new HashMap<String, Item>(19); //Creating a map to store only checked itesm
            int i = 0;
     
            writeStrings(out, top); //Printing the HTML headers
     
            if (selected != null & !(selected.length == 0)) {
                out.println("<p>You selected:</p>"
                        + "<table style='border-collapse:collapse'><tr><th>Designer</th><th>Price</th></tr>");
                for (String buy : selected) { //Runs each time a "buy" item is checked
                    if (buy != null && !buy.isEmpty()) {
                        Item myItem = itemMap.get(buy);
                        total += myItem.getPrice(); //Adds the value of the item to the total
                        checkedItems.put(myItem.getName(), myItem); //Creates a map of only checked items
                        prices[i] = myItem.getPrice(); //Sends the prices into an array so it can be printed in a table later
                        i++;
                    }
                }
     
                for (i = 0; i < selected.length; i++) {
                    out.println("<tr><td style='border-style:solid; border-width:1px'>" + selected[i]
                            + "</td><td style='border-style:solid; border-width:1px'> $" + df.format(prices[i]) + "</tr>");
                } 
     
                if (tax != null) {
                    out.println("</table>" + "<p>Your sub-total is: $" + total);
                    total *= 1.06;
                    out.println("<br>Your total after 6% tax is $" + df.format(total) + "</p>"
                            + "<form action='Cart' method='GET'>"
                            + "<input type='submit' name='Cart' value='Go back'></form>");
                } else {  
                    out.println("</table>" + "<p>Your total is $" + df.format(total) + "</p>"
                            + "<form action='Cart' method='GET'> "
                            + "<input type='submit' name='Cart' value='Go back'></form>");
                }
                writeStrings(out, bottom);
            } else {
                out.println("Nothing selected");
                out.println("<form action='Cart' method='GET'> \n"
                        + "<input type='submit' name='Cart' value='Go back'></form>");
                writeStrings(out, bottom);
            }
     
        }
     
        private static String[] top = {
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "<title>Dresses</title>",
            "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>",
            "</head>",
            "<body>"
        };
        private static String[] middle = {
            "<h1 style='text-align:center'>Bridesmaid Dresses</h1>",
            "<form action='Cart' method='POST'>",
            "<table style='border-style:solid; border-width:1px; border-collapse:collapse'>"
        };
        private static String[] formEnd = {
            "</table> \n" + "<p><input type='checkbox' name='md' value='md'> Check this box if you are a Maryland resident.</p>\n"
            + "<input type='submit' name='Total' value='Total'>\n"
            + "</form>\n"
            + "<p>When the 'total' button is checked, a shopping cart page is displayed which shows the total cost for all checked items. If the Maryland resident box is checked, 6% tax is added to the total price. The back button on the shopping cart page will return you to this page, and the selected values will still be selected.</p>\n"
            + "<small>Created by Tenley, ID: 0129508</small>"
        };
        private static String[] bottom = {
            "</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);
            }
            out.flush();
        }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,360
    Thanks
    49
    Thanked 2,207 Times in 2,180 Posts

    Default Re: Using an If statement to check boxes

    giving an illegal start of expression error.
    Please copy the full text of the error message and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. how to add two check boxes into single line
    By starhanif in forum Java ME (Mobile Edition)
    Replies: 4
    Last Post: September 4th, 2013, 07:38 AM
  2. boxes
    By keepStriving in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 8th, 2013, 05:59 PM
  3. Disabling Check Boxes created by different method.
    By xdega in forum AWT / Java Swing
    Replies: 3
    Last Post: April 23rd, 2012, 11:06 AM
  4. Strange boxes appearing
    By fishnj1333 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 11th, 2012, 05:36 AM
  5. how to write an if statement which evaluates 3 dialogue boxes
    By humdinger in forum Loops & Control Statements
    Replies: 6
    Last Post: January 14th, 2010, 12:28 PM