网上音乐光碟商城
Disks.java
package musicshoppro;
public class Disks {
//创建保存音乐光碟信息的数组,数据是编的啊
String[][]disks={
{"跨时代专辑","周杰伦","唱片公司1","13"},
{"江南专辑","林俊杰","唱片公司2","31"},
{"火力全开专辑","王力宏","唱片公司3","29"},
{"玩酷专辑","潘玮柏","唱片公司4","15"},
{"乐行者专辑","林俊杰","唱片公司2","12"},
{"十一月的肖邦","周杰伦","唱片公司1","57"}
};
//创建保存商品数量的数组
int[] cartQuantities=new int[disks.length];
//返回音乐光碟数组
public String[][] getDisks()
{
return disks;
}
//增加购物车商品的数量
public void addQuantity(int pos,int quantity)throws Exception{
//检查增加的数量是否大于0
if(quantity>0){
cartQuantities[pos]+=quantity;
}else{
throw new Exception("增加的数量小于或者等于-.");
}
}
//减少购物车商品的数量
public void minusQuantity(int pos,int quantity)throws Exception{
//检查减少数量的余额是否小于0
if(cartQuantities[pos]-quantity>=0){
cartQuantities[pos]-=quantity;
}else{
throw new Exception("减少的数量大于该光碟的订碟数量.");
}
}
//返回购物车的商品名称,价格,数量和金额
public String[][] getCartDisks(){
//创建购物车的商品数组
String[][] cartDisksTemp=new String[disks.length][4];
//创建保存购物车总金额的变量
double amount=0;
//创建保存购物车商品总数的变量
int diskNum=0;
for(int i=0;i<cartQuantities.length;i++)
{
if(cartQuantities[i]>0)
{
//存入商品名称
cartDisksTemp[i][0]=disks[i][0];
//存入商品价格
cartDisksTemp[i][1]=disks[i][3];
double price=Double.parseDouble(disks[i][3]);
//存入商品的数量
cartDisksTemp[i][2]=String.valueOf(cartQuantities[i]);
//计算商品的金额
double oneAmount=price*cartQuantities[i];
//存入商品的金额
cartDisksTemp[i][3]=String.valueOf(oneAmount);
//累加商品的总金额
amount+=oneAmount;
//累加购物车商品总数
diskNum++;
}
}
//重新创建购物车商品数组,+1行保存总金额
String[][] cartDisks=new String[diskNum+1][4];
//删除数组内的空行
int k=0;
for(int i=0;i<cartQuantities.length;i++)
{
if(cartQuantities[i]>0)
{
for(int j=0;j<4;j++)
{
cartDisks[k][j]=cartDisksTemp[i][j];
}
k++;
}
}
//存入购物车的总金额
cartDisks[cartDisks.length-1][0]="总金额";
cartDisks[cartDisks.length-1][3]=String.valueOf(amount);
return cartDisks;
}
}
ShowDisks.jsp
<%@ page language="java" contentType="text/html; charset=GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"></html>
ShowCartDisks.jsp
<%@ page language="java" contentType="text/html; charset=GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>显示购物车商品</title>
</head>
<body>
<jsp:useBean id="disks" scope="session" class="musicshoppro.Disks"/>
<center>
<h3>购物车的商品如下图所示</h3>
<%
//取得购物车的商品
String[][] cartDisks=disks.getCartDisks();
%>
<table width="80%" border="1">
<tr>
<td>光碟名称</td>
<td>价钱</td>
<td>数量</td>
<td>金额</td>
</tr>
<%
for(int i=0;i<cartDisks.length-1;i++)
{
%>
<tr>
<td><%=cartDisks[i][0]%></td>
<td><%=cartDisks[i][1]%></td>
<td><%=cartDisks[i][2]%></td>
<td><%=cartDisks[i][3]%></td>
</tr>
<%
}
%>
<%--显示总金额 --%>
<tr>
<td><%=cartDisks[cartDisks.length-1][0] %></td>
<td colspan="2"> </td>
<td><%=cartDisks[cartDisks.length-1][3] %></td>
</tr>
</table>
</center>
</body>
</html>