《JAVA开发实战经典》P239练习

《JAVA开发实战经典》P239练习


6.使用面向对象的概念表示出下面的生活场景:
小明去超市买东西,所有买到的东西都放在了购物车当中,最后到收银台一起结账。

快捷键

interface Goods{
    public String getName();
    public double getPrice();
}
class Toys implements Goods{
    private String name;
    private double price;
    public String getName() {
        return this.name;
    }
    public double getPrice(){
        return this.price;
    }
    Toys(String name,double price){
        this.name = name;
        this.price = price;
    }
}


class Clothes implements Goods{
    private String name;
    private double price;
    public double getPrice(){
        return this.price;
    }
    public String getName() {
        return this.name;
    }
    Clothes(String name,double price){
        this.name = name;
        this.price = price;
    }
}

class Drinks implements Goods{
    private String name;
    private double price;
    public double getPrice(){
        return this.price;
    }
    public String getName() {
        return this.name;
    }
    Drinks(String name,double price){
        this.name = name;
        this.price = price;
    }
}

class Foods implements Goods{
    private String name;
    private double price;
    public double getPrice(){
        return this.price;
    }
    public String getName() {
        return this.name;
    }
    Foods(String name,double price){
        this.name = name;
        this.price = price;
    }
}
class ShoppingCart{
    private Goods Good[];
    private int foot;
    static int addlen = 1;
    private double total;
    public ShoppingCart(int len){
        if (len > 1){
            Good = new Goods[len];
        }else{
            Good = new Goods[1];
        }

    }
    //定义购物篮大小,添加商品
    public void add(Goods good){
        if (this.foot >= Good.length){
            Goods goods[] = new Goods[this.Good.length + addlen];
            System.arraycopy(this.Good,0,goods,0,this.Good.length);
            this.Good = goods;
        }
        this.Good[this.foot] = good;
        foot++;
    }
    //计算总价
    public double totalMoney(){
        for (int i = 0; i < Good.length; i++) {
            total += Good[i].getPrice();
        }
        return this.total;
    }
    //计总件数
    public int totalCount(){
        return foot;
    }
}

public class Main{
    public static void main(String[] args) {
        ShoppingCart sc = new ShoppingCart(1);
        sc.add(new Toys("手枪",25.5));
        sc.add(new Toys("飞机",84.3));
        sc.add(new Drinks("特伦舒(箱)",73.5));
        sc.add(new Foods("乐事薯片",8.5));
        sc.add(new Clothes("牛仔裤",120));
        sc.add(new Clothes("白T",60));
        System.out.println("总共买了" + sc.totalCount() + "商品" + ";共计" + sc.totalMoney() + "元");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值