import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 定义存储汽车对象的数组
Car[] cars = new Car[3];
// 录入并创建三个汽车对象
for (int i = 0; i < cars.length; i++) {
System.out.println("请输入第" + (i + 1) + "辆汽车的品牌:");
String brand = scanner.next();
System.out.println("请输入第" + (i + 1) + "辆汽车的价格:");
double price = scanner.nextDouble();
System.out.println("请输入第" + (i + 1) + "辆汽车的颜色:");
String color = scanner.next();
// 创建汽车对象并存入数组
cars[i] = new Car(brand, price, color);
}
// 计算平均价格
double sumPrice = 0;
for (Car car : cars) {
sumPrice += car.getPrice();
}
double averagePrice = sumPrice / cars.length;
// 打印每台汽车的信息和平均价格
for (Car car : cars) {
System.out.println(car);
}
System.out.println("三台汽车的平均价格是:" + averagePrice);
// 关闭Scanner
scanner.close();
}
}
public class Car {
private String brand;
private double price;
private String color;
// 标准getter和setter方法
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
// 构造方法
public Car(String brand, double price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
// toString方法用于打印汽车信息
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
", color='" + color + '\'' +
'}';
}
}