public class Phone {//手机类
private String brand;//品牌
private int price;//价格
private String color;//颜色
public Phone() {//空参构造方法
}
public Phone(String brand,int price,String color) {//带参构造方法
this.brand=brand;
this.price=price;
this.color=color;
}//生成getter和setter方法
//形成经典的javaBean
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
public class PhoneTest {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Phone[] arr=new Phone[3];//创建一个数组长度是3存储数据
Phone p1=new Phone("小米",2999,"红色");//三种手机的属性
Phone p2=new Phone("华为",4999,"白色");
Phone p3=new Phone("魅族",1999,"蓝色");
arr[0]=p1;//将数据存储到数组中
arr[1]=p2;
arr[2]=p3;
int sum=0;//创建一个变量进行储存总价格
for(int i=0;i<arr.length;i++) {
Phone phone=arr[i];//创建对象用于规范也可以直接使用arr[i]
sum=sum+phone.getPrice();
}
int pin=sum/arr.length;//总价格除以数量得到平均价格
System.out.println("三种手机的平均价格为"+pin);//输出平均价格
}
}