汽车java做业

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 + '\'' +
                '}';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值