题目要求:
/*定义数组存储3部手机对象
* 手机的属性:品牌,价格,颜色
* 要求,计算出三部手机的平均价格*/
代码实现:
定义一个包,里面新建两个类,Phone和PhoneTest
代码解读:需要在Phone里面写Javabean的代码
Phone类的内容
package Text6;
/*定义数组存储3部手机对象
* 手机的属性:品牌,价格,颜色
* 要求,计算出三部手机的平均价格*/
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;
}
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;
}
}
PhoneTest类的内容
package Text6;
public class PhoneText {
public static void main(String []args) {
//1.创建一个数组
Phone[]arr=new Phone[3];
//2.创建手机的对象
Phone p1=new Phone("华为",4000,"白色");
Phone p2=new Phone("三星",5000,"黑色");
Phone p3=new Phone("苹果",9000,"蓝色");
//3.把对象存储到数组中
arr[0]=p1;
arr[1]=p2;
arr[2]=p3;
//获取三部手机的平均价
int sum=0;
for(int i=0;i<arr.length;i++) {
//i索引 arr[i]对象
Phone phone=arr[i];
sum=sum+phone.getPrice();
}
//求平均值
//数据能不写死,就不写死
int avg=sum/arr.length;
double avg2=sum*1.0/arr.length;
System.out.println(avg);
System.out.println(avg2);
}
}
运行结果