java如何调用自定义类型数组中嵌套的自定义数组的各个属性(定义一个Product类,类中属性name(String 商品名字),price(double),count(int 订单数量)...)

定义多个用户,一个用户有多个商品组成的订单,如何深度调用某个用户的某个商品名,商品总价值,订单信息等等

如题:
定义一个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("------");
	}
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值