成都创新互联网站制作重庆分公司

java购物车源代码,购物商城java源代码

Java初学者,哪位友友能帮我设计一个简单的类似超市购物车的程序,参考一下~谢谢!

以前学习java又做个实例,挺值得学习的。

网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、小程序制作、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了织金免费建站欢迎大家使用!

1.首先我先列出我们所需要的java类结构。

1)Database.java --------- 模拟存储商品的数据库。

2)McBean.java ------------ 商品实体类,一个普通的javabean,里面有商品的基本属性。

3)OrderItemBean.java --- 订单表。

4)ShoppingCar.java ------ 这个就是最主要的购物车,当然比较简单。

5)TestShoppingCar.java --- 这个是测试类。

2.下面贴出具体代码并带关键注释。

---Database.java

public class Database {

/*采用Map存储商品数据,为什么呢?我觉得这个问题你自己需要想下。

* Integer 为Map的key值,McBean为Map的value值。

*/

private static MapInteger, McBean data = new HashMapInteger, McBean();

public Database() {

McBean bean = new McBean();

bean.setId(1);

bean.setName("地瓜");

bean.setPrice(2.0);

bean.setInstuction("新鲜的地瓜");

data.put(1, bean);//把商品放入Map

bean = new McBean();

bean.setId(2);

bean.setName("土豆");

bean.setPrice(1.2);

bean.setInstuction("又好又大的土豆");

data.put(2, bean);//把商品放入Map

bean = new McBean();

bean.setId(3);

bean.setName("丝瓜");

bean.setPrice(1.5);

bean.setInstuction("本地丝瓜");

data.put(3, bean);//把商品放入Map

}

public void setMcBean(McBean mcBean){

data.put(mcBean.getId(),mcBean);

}

public McBean getMcBean(int nid) {

return data.get(nid);

}

}

---McBean.java

public class McBean {

private int id;//商品编号

private String name;//商品名

private double price;//商品价格

private String instuction;//商品说明

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

public String getInstuction() {

return instuction;

}

public void setInstuction(String instuction) {

this.instuction = instuction;

}

}

---ShoppingCar.java

public class ShoppingCar {

private double totalPrice; // 购物车所有商品总价格

private int totalCount; // 购物车所有商品数量

private MapInteger, OrderItemBean itemMap; // 商品编号与订单项的键值对

public ShoppingCar() {

itemMap = new HashMapInteger, OrderItemBean();

}

public void buy(int nid) {

OrderItemBean order = itemMap.get(nid);

McBean mb;

if (order == null) {

mb = new Database().getMcBean(nid);

order = new OrderItemBean(mb, 1);

itemMap.put(nid, order);

update(nid, 1);

} else {

order.setCount(order.getCount() + 1);

update(nid, 1);

}

}

public void delete(int nid) {

OrderItemBean delorder = itemMap.remove(nid);

totalCount = totalCount - delorder.getCount();

totalPrice = totalPrice - delorder.getThing().getPrice() * delorder.getCount();

}

public void update(int nid, int count) {

OrderItemBean updorder = itemMap.get(nid);

totalCount = totalCount + count;

totalPrice = totalPrice + updorder.getThing().getPrice() * count;

}

public void clear() {

itemMap.clear();

totalCount = 0;

totalPrice = 0.0;

}

public void show() {

DecimalFormat df = new DecimalFormat("¤#.##");

System.out.println("商品编号\t商品名称\t单价\t购买数量\t总价");

Set set = itemMap.keySet();

Iterator it = set.iterator();

while (it.hasNext()) {

OrderItemBean order = itemMap.get(it.next());

System.out.println(order.getThing().getId() + "\t"

+ order.getThing().getName() + "\t"

+ df.format(order.getThing().getPrice()) + "\t" + order.getCount()

+ "\t" + df.format(order.getCount() * order.getThing().getPrice()));

}

System.out.println("合计: 总数量: " + df.format(totalCount) + " 总价格: " + df.format(totalPrice));

System.out.println("**********************************************");

}

}

---OrderItemBean.java

public class OrderItemBean {

private McBean thing;//商品的实体

private int count;//商品的数量

public OrderItemBean(McBean thing, int count) {

super();

this.thing = thing;

this.count = count;

}

public McBean getThing() {

return thing;

}

public void setThing(McBean thing) {

this.thing = thing;

}

public int getCount() {

return count;

}

public void setCount(int count) {

this.count = count;

}

}

---TestShoppingCar.java

package com.shop;

public class TestShoppingCar {

public static void main(String[] args) {

ShoppingCar s = new ShoppingCar();

s.buy(1);//购买商品编号1的商品

s.buy(1);

s.buy(2);

s.buy(3);

s.buy(1);

s.show();//显示购物车的信息

s.delete(1);//删除商品编号为1的商品

s.show();

s.clear();

s.show();

}

}

3.打印输出结果

商品编号 商品名称 单价 购买数量 总价

1 地瓜 ¥2 3 ¥6

2 土豆 ¥1.2 1 ¥1.2

3 丝瓜 ¥1.5 1 ¥1.5

合计: 总数量: ¥5 总价格: ¥8.7

**********************************************

商品编号 商品名称 单价 购买数量 总价

2 土豆 ¥1.2 1 ¥1.2

3 丝瓜 ¥1.5 1 ¥1.5

合计: 总数量: ¥2 总价格: ¥2.7

**********************************************

商品编号 商品名称 单价 购买数量 总价

合计: 总数量: ¥0 总价格: ¥0

**********************************************

4.打字太累了,比较匆忙,但是主要靠你自己领会。哪里不清楚再提出来。

jsp购物车代码

//shopping.html

html

headtitleshopping stor/title/head

body

form action="carts.jsp" target="post"

br

please select the item that you want to buy

br

select name="item"

optionbook:old man and the sea

optionx-box game machine

optionmp3 player

optioncce

optionbook:jsp programming

optioncd "the endless love"

optiondvd "gone with the wind"

/select

br

input type="submit" name="submit" value="add"

input type="submit" name="submit" value="remove"

/form

/body

/html

------------------------------------------------------------------

//carts.jsp

%@page contentType="text/html;charset=ISO8859_1" %

html

jsp:useBean id="cart" scope="session" class="test.DummyCart"/

jsp:setProperty name="cart" property="*"/

%

cart.processRequest();

%

br

ol

you have chosen these items:

%

String []items=cart.getItems();

for(int i=0;iitems.length;i++)

{

%

li%=items[i] %/li

%

}

%

/ol

hr

%@include file="shopping.htm" %

/html

---------------------------------------------------------------------//DummyCart.java

package test;

import javax.servlet.http.*;

import java.util.Vector;

import java.util.Enumeration;

public class DummyCart

{

Vector v = new Vector();

String submit=null;

String item= null;

private void addItem(String name)

{

v.addElement(name);

}

private void removeItem(String name)

{

v.removeElement(name);

}

public void setItem(String s)

{

item=s;

}

public void setSubmit(String s)

{

submit=s;

}

public String[] getItems()

{

String []s=new String[v.size()];

v.copyInto(s);

return s;

}

public void processRequest()

{

if(submit==null)

addItem(item);

if(submit.equals("add"))

addItem(item);

else if (submit.equals("remove"))

removeItem(item);

reset();

}

private void reset()

{

submit=null;

item=null;

}

}

----------------------------------------------------------------------

上面是一个简单的例子,功能都能实现,对网页效果要求更漂亮些的可做一些修改。

编程 java 关于购物车

点击数量进入购物车页面,这个应该好做吧,跳动一个Action转发到购物车页面

下面是我的图书购物车(自己写的)

package com.jc.ts.services;

import java.math.BigDecimal;

import java.util.Collection;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import com.jc.ts.entity.BookCar;

import com.jc.ts.entity.BookInfo;

/**

* 该类提供购物车的操作

* */

public class CartItemsService {

private MapString,BookCar itemMap=null;//购物车Map集合

private CollectionBookCar items;//购物车项

public CartItemsService()

{

itemMap=new HashMapString ,BookCar();

}

public CollectionBookCar getItems() {

return items;

}

public void setItems(CollectionBookCar items) {

this.items = items;

}

public MapString, BookCar getItemMap() {

return itemMap;

}

public void setItemMap(MapString, BookCar itemMap) {

this.itemMap = itemMap;

}

public int getBookCarSize()

{

return itemMap.size();

}

public boolean containById(String bookid)

{

return itemMap.containsKey(bookid);

}

public void addBookCarItems(BookInfo bookInfo)

{

if(bookInfo!=null)

{

BookCar bookCar=(BookCar)itemMap.get(bookInfo.getBid());

if(bookCar==null)

{

bookCar=new BookCar();

bookCar.setBookinfo(bookInfo);

bookCar.increaseQuantity();

itemMap.put(bookInfo.getBid(),bookCar);

items=itemMap.values();

}else {

bookCar.increaseQuantity();

}

}

}

public BookInfo removeCarItem(String bookid)

{

BookCar bookCar=itemMap.remove(bookid);

if(bookCar==null)

{

return null;

}

items=itemMap.values();

return bookCar.getBookinfo();

}

public BigDecimal getBookCarTotal()//获得总金额

{

BigDecimal carTotal=new BigDecimal("0.00");

IteratorBookCar iterator=this.getAllCartItems();

while(iterator.hasNext())

{

BookCar bookCar=iterator.next();

BigDecimal carPrice=bookCar.getBookinfo().getBprice();

BigDecimal quantity=new BigDecimal(String.valueOf(bookCar.getQuantity()));

carTotal=carTotal.add(carPrice.multiply(quantity));

}

return carTotal;

}

public IteratorBookCar getAllCartItems(){

return itemMap.values().iterator();

}

public void increaseQuantityById(String bookid)

{

BookCar bookCar=itemMap.get(bookid);

if(bookCar!=null)

{

bookCar.increaseQuantity();

}

}

public void setQuantityById(String bookid,int quantity)//根据图书ID增加数量

{

BookCar bookCar=itemMap.get(bookid);

if(bookCar!=null)

{

bookCar.setQuantity(quantity);

}

}

public void clear(){

itemMap.clear();

}

}

修改后传入这个方法就可以了setQuantityById()

★★★ 注意购物车一定要用Map 不能用List或ArrayList

因为购物车是顾客频繁操作的功能

Map在取值或删除值的效率比List或ArrayList要高的多

它基本不需要时间,而List或ArrayList还要遍历。。。。。。

希望对你有帮助!!

java中servlet的购物车程序是怎么样的流程?

购买过程就是选择好物品放入购物车然后结账

import java.util.Vector;public class gouwuche { /**

* @param args

*/

private static Vector vec = new Vector();

public static void gw(String name,int price,int sum)

{

gouwuchebean bean;

if(vec.size()0)

{

//说明购物车内有物品 进来比对 看是否有一样的东西 有的话让数量+sum

bean = new gouwuchebean();

int j=0;//用来计数

for(int i=0;ivec.size();i++)

{

gouwuchebean bean1 = (gouwuchebean)vec.get(i);

if(bean1.getName().equals(name))

{

j++;

bean.setName(name);

bean.setPrice(price);

bean.setSum(sum+bean1.getSum());

vec.remove(i);//去掉原来的数据

vec.add(bean);//放入新的数据

}

}

if(j==0)

{

bean.setName(name);

bean.setPrice(price);

bean.setSum(sum);

vec.add(bean);

}

}

else

{

//如果集合是空的说明购物车内没有重复的 直接放入即可

bean = new gouwuchebean();

bean.setName(name);

bean.setPrice(price);

bean.setSum(sum);

vec.add(bean);

}

}

public static void show()

{

System.out.println("=============购物车当前物品==============");

int sum = 0;//用来计一共有几件物品

int pric = 0;//用来计共消费金额

for(int i=0;ivec.size();i++)

{

gouwuchebean bean = (gouwuchebean)vec.get(i);

sum = sum+bean.getSum();

pric = pric+(bean.getPrice()*bean.getSum());

System.out.println("*第"+(i+1)+"种物品-----名称:"+bean.getName()+"---数量是:"+bean.getSum()+"---单价是:"+bean.getPrice()+"元----共计"+(bean.getSum()*bean.getPrice()+"元"));

}

System.out.println("物品共计"+sum+"件 共计金额是:"+pric+"元");

System.out.println("=============欢迎使用购物车==============");

}

public static void main(String[] args) {

// TODO Auto-generated method stub gw("电视机",100,1);//选择购买物品 价格和数量还有名字

gw("可口可乐",100,9);

gw("电视机",100,9);

gw("西瓜",10,5);

gw("电动车",3000,2);

gw("奥迪A6",4000000,2);

show();

}}测试结果

java简单的购物车代码

package Test;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

init();//初始化

MapString,String map = new LinkedHashMap();

while(true){

Scanner in= new Scanner(System.in);

map = buy(in,map);//选择

System.out.println();

System.out.println("还要继续购物吗?(Y/N)");

String jx = in.nextLine();

if(jx.equals("N")){

break;

}

}

print(map);

}

public static void print(MapString, String m){

System.out.println("\n\n\n******************");

System.out.println("       购物车清单");

Integer hj = 0;

for (EntryString, String entry : m.entrySet()) {

String key = entry.getKey();

String value = entry.getValue();

if(key.equals("1")){

hj += Integer.parseInt(value)*3;

System.out.println("哇哈哈纯净水: "+value+"件,合计:¥"+Integer.parseInt(value)*3);

}else if(key.equals("2")){

hj += Integer.parseInt(value)*5;

System.out.println("康师傅方便面: "+value+"件,合计:¥"+Integer.parseInt(value)*5);

}else if(key.equals("3")){

hj += Integer.parseInt(value)*4;

System.out.println("可口可乐: "+value+"件,合计:¥"+Integer.parseInt(value)*4);

}

}

System.out.println("合计金额:¥"+hj);

}

public static void init(){

System.out.println("******************");

System.out.println("\t商品列表\n");

System.out.println("              商品名称                价格");

System.out.println("1.   哇哈哈纯净水        ¥3");

System.out.println("2.   康师傅方便面        ¥5");

System.out.println("3.   可口可乐                ¥4");

System.out.println("******************");

}

public static MapString,String buy(Scanner scan,MapString,String m){

System.out.print("请输入编号:");

String bh = scan.nextLine();

System.out.print("请输入购买数量:");

String num = scan.nextLine();

if(m.size()0  m.keySet().contains(bh)){

m.put(bh,(Integer.parseInt(bh)+Integer.parseInt(num))+"");

}else{

m.put(bh, num);

}

return m;

}

}

java 如何编写购物车

用Vector 或者是HashMap去装

下面有部分代码你去看吧

package com.aptech.restrant.DAO;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.sql.Connection;

import com.aptech.restrant.bean.CartItemBean;

import com.aptech.restrant.bean.FoodBean;

public class CartModel {

private Connection conn;

public CartModel(Connection conn) {

this.conn=conn;

}

/**

* 得到订餐列表

*

* @return

*/

public List changeToList(Map carts) {

// 将Set中元素转换成数组,以便使用循环进行遍历

Object[] foodItems = carts.keySet().toArray();

// 定义double变量total,用于存放购物车内餐品总价格

double total = 0;

List list = new ArrayList();

// 循环遍历购物车内餐品,并显示各个餐品的餐品名称,价格,数量

for (int i = 0; i foodItems.length; i++) {

// 从Map对象cart中取出第i个餐品,放入cartItem中

CartItemBean cartItem = (CartItemBean) carts

.get((String) foodItems[i]);

// 从cartItem中取出FoodBean对象

FoodBean food1 = cartItem.getFoodBean();

// 定义int类型变量quantity,用于表示购物车中单个餐品的数量

int quantity = cartItem.getQuantity();

// 定义double变量price,表示餐品单价

double price = food1.getFoodPrice();

// 定义double变量,subtotal表示单个餐品总价

double subtotal = quantity * price;

// // 计算购物车内餐品总价格

total += subtotal;

cartItem.setSubtotal(subtotal);

cartItem.setTotal(total);

list.add(cartItem);

}

return list;

}

/**

* 增加订餐

*/

public Map add(Map cart, String foodID) {

// 购物车为空

if (cart == null) {

cart = new HashMap();

}

FoodModel fd = new FoodModel(conn);

FoodBean food = fd.findFoodById(foodID);

// 判断购物车是否放东西(第一次点餐)

if (cart.isEmpty()) {

CartItemBean cartBean = new CartItemBean(food, 1);

cart.put(foodID, cartBean);

} else {

// 判断当前菜是否在购物车中,false表示当前菜没有被点过。。

boolean flag = false;

// 得到键的集合

Set set = cart.keySet();

// 遍历集合

Object[] obj = set.toArray();

for (int i = 0; i obj.length; i++) {

Object object = obj[i];

// 如果购物车已经存在当前菜,数量+1

if (object.equals(foodID)) {

int quantity = ((CartItemBean) cart.get(object))

.getQuantity();

quantity += 1;

System.out.println(quantity);

((CartItemBean) cart.get(object)).setQuantity(quantity);

flag = true;

break;

}

}

if (flag == false) {

// 把当前菜放到购物车里面

CartItemBean cartBean = new CartItemBean(food, 1);

cart.put(foodID, cartBean);

}

}

return cart;

}

/**

* 取消订餐

*/

public Map remove(Map cart, String foodID) {

cart.remove(foodID);

return cart;

}

/**

* 更新购物车信息

*

* @param cart

* @param foodID

* @return

*/

public MapString, CartItemBean update(Map cart, String foodID,

boolean isAddorRemove) {

Map map;

if (isAddorRemove) {

map = add(cart, foodID);

} else {

map = remove(cart, foodID);

}

return map;

}

}


本文题目:java购物车源代码,购物商城java源代码
标题来源:http://cxhlcq.com/article/heesei.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部