定义数组存储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);
}
}