练习:对象数组 3
定义数组存储 3 部手机对象。手机的属性:品牌,价格,颜色。要求,计算出三部手机的平均价格。
代码:
//对象数组 3
package demo01;
public class Phone {private String brand;private int price;private String colour;public Phone() {}public Phone(String brand, int price, String colour) {this.brand = brand;this.price = price;this.colour = colour;}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 getColour() {return colour;}public void setColour(String colour) {this.colour = colour;}
}
//对象数组 3
package demo01;
public class PhoneDemo {public static void main(String[] args) {Phone[] array = new Phone[3];Phone p1 = new Phone("红米Redmi Note 14", 52800, "星辉白");Phone p2 = new Phone("华为 Pura70", 29999, "雪域白");Phone p3 = new Phone("vivo Y37", 49499, "月影黑");array[0] = p1;array[1] = p2;array[2] = p3;int sum = 0;for(int i = 0; i < array.length; i++) {sum += array[i].getPrice();}double avg = (double) sum / array.length;System.out.println("三部手机的平均价格为:" + String.format("%.2f", avg));}
}
运行结果: