Reda93
Reda93

Reputation: 23

Add and print values from a session in Java Servlets?

Ok, I have this shopping cart code that out.println different game name, quantity and price whenever any 'add to cart' button is pressed. The problem is, let's say I buy 2 pcs of the same game and 2 pcs of another, it will display the total amount of each game and not the total amount of all the games.

So, what I am having trouble at is calculating the total amount of all games and printing it all together, then I want to write the value to a file together with the name of the game.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cart extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String s, goods[] = {"Fifa 15", "Battlefield 4", "GTA 5", "The Last of US"};
int price []={59,49,69,39};
int cost;
PrintWriter out = res.getWriter();
res.setContentType("text/html");
HttpSession session = req.getSession(true);

if ( session == null ) return;
for (int i = 0; i < goods.length; i++){
    if ( session.getAttribute(goods[i]) == null )
    session.setAttribute(goods[i], new Integer(0));}

if ((s = req.getParameter("fifa")) != null) {
        int n = ((Integer) session.getAttribute(goods[0])).intValue();
        session.setAttribute(goods[0], new Integer(n + 1));
    } else if ((s = req.getParameter("battle")) != null) {
        int n = ((Integer) session.getAttribute(goods[1])).intValue();
        session.setAttribute(goods[1], new Integer(n + 1));
    } else if ((s = req.getParameter("gta")) != null) {
        int n = ((Integer) session.getAttribute(goods[2])).intValue();
        session.setAttribute(goods[2], new Integer(n + 1));
    } else if ((s = req.getParameter("lou")) != null) {
        int n = ((Integer) session.getAttribute(goods[3])).intValue();
        session.setAttribute(goods[3], new Integer(n + 1));
    }
out.println("<html><body><h2>Shopping Cart:</h2><ul>");
out.println("Items that have been Successfully added to Your Shopping Cart: ");
out.println();
for (int i = 0; i < goods.length; i++) {
    int n = ((Integer)session.getAttribute(goods[i])).intValue();
    if ( n > 0 )
    {out.println("<li><b>" + goods[i] + "</b> : " + n +" pcs for the price of $"+price[i] +"</li>");
        cost=n*price[i];
        out.println("$"+cost);}
    }
out.println("</ul></body></html>");

Upvotes: 1

Views: 551

Answers (1)

tetram
tetram

Reputation: 305

If I undestand well, you want the total ?

int n;
int total = 0;
for (int i = 0; i < goods.length; i++) {
    n = ((Integer)session.getAttribute(goods[i])).intValue();
    if ( n > 0 ) {
        out.println("<li><b>" + goods[i] + "</b> : " + n +" pcs for the price of $"+price[i] +"</li>");
        cost=n*price[i];
        total=total+cost;
        out.println("$"+cost);
    }
    out.println("Total is : $"+total);
}

Upvotes: 1

Related Questions