【java】作业2

定义数组存储3部手机对象。

手机的属性:品牌、价格、颜色。

要求:计算三部手机的平均价格。

class Phone{
    private String brand;
    private double price;
    private String color;

    public Phone(String brand,double price,String color){
        this.brand=brand;
        this.price=price;
        this.color=color;
    }

    public  String getBrand(){
        return brand;
    }

    public  double getPrice(){
        return price;
    }

    public String getColor(){
        return color;
    }

    public void setPrice(){
        if(price<0){
            System.out.println("price cannot be a negative.");
        }else{
            this.price=price;
        }
    }
}

public  class Main {
    public static void main(String[] args) {
        Phone[] phones=new Phone[3];

        phones[0]=new Phone("huawei",12345,"red");
        phones[1]=new Phone("iphone",12321,"white");
        phones[2]=new Phone("sansum",21321,"pink");

        double totalPrice=0;
        for(Phone phone:phones){
            totalPrice+=phone.getPrice();
        }
        double averagePrice=totalPrice/phones.length;

        System.out.println("the average price is:"+averagePrice);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值