定义多个用户,一个用户有多个商品组成的订单,如何深度调用某个用户的某个商品名,商品总价值,订单信息等等
如题:
定义一个Product类,类中属性name(String 商品名字),price(double),count(int 订单数量),属性私有提供set/get方法showMessage,展示商品信息
定义一个Order类,类中属性id(int 订单编号),name(String 用户姓名),Product[] (商品信息 每个订单包含多个商品)
方法showOrder,用来展示订单详情
创建多个Order对象保存在Order类型的数组中,获取每一个订单总价。
package pack1;
public class Test {
public static void main(String[] args) {
Product[] p1=new Product[]{new Product ("花生",20.0,5),
new Product("瓜子",10.0,3)
};
Product[] p2=new Product[]{new Product ("农夫山泉",2.0,2),
new Product("可乐",3.0,1)
};
Order[] o=new Order[]{
new Order(1, "张三",p1),
new Order(2, "李四",p2),
};
//打印每位用户商品信息
for (int i = 0; i < o.length; i++) {
o[i].showOrder();
}
for (int i = 0; i < o.length; i++) {
//定义每位用户的订单总价
double sumprice=0;
for (int j = 0; j < o[i].getProduct().length; j++) {
sumprice=sumprice+o[i].getProduct()[j].getPrice()*
o[i].getProduct()[j].getCount();
}
System.out.println(o[i].getName()+"的订单总价:"+sumprice);
}
}
}
class Product{
private String name;
private double price;
private int count;
public Product(String name,double price,int count) {
this.name=name;
this.price=price;
this.count=count;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public void setCount(int count) {
this.count = count;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getCount() {
return count;
}
public void showMessage() {
System.out.println("名字:"+getName()+
"价格:"+getPrice()
);
}
}
class Order {
private int id;
private String name;
private Product[] product;
public Order(int id,String name,Product[] product){
this.id=id;
this.name=name;
this.product=product;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setProduct(Product[] product) {
this.product = product;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Product[] getProduct() {
return product;
}
public void showOrder() {
System.out.println("id:"+getId()+
" 姓名:"+getName());
for (int i = 0; i < product.length; i++) {
System.out.println("商品名:"+product[i].getName()+
" 价格:"+product[i].getPrice()+
" 数量:"+product[i].getCount()
);
}
System.out.println("------");
}
}