通过java实现根据封装的知识,编写程序,题目要求: 某汽车销售公司,销售各种小车,有品牌,型号,座位数,颜色,单价,上个月销售量等属性,及计算月销售金额方法。 要求:(1)创建 Car 类封装上述属性与方法。 (2)创建测试类,实例化多部小车,键盘输入数据,以表格形式输出
时间: 2023-05-21 20:04:54 浏览: 385
非常好的问题,下面是代码示例:
```java
public class Car {
private String brand;
private String model;
private int seats;
private String color;
private double unitPrice;
private int lastMonthSales;
public Car(String brand, String model, int seats, String color, double unitPrice, int lastMonthSales) {
this.brand = brand;
this.model = model;
this.seats = seats;
this.color = color;
this.unitPrice = unitPrice;
this.lastMonthSales = lastMonthSales;
}
public double calculateSalesAmount() {
return this.unitPrice * this.lastMonthSales;
}
public String toString() {
return String.format("%s %s %d座 %s色 单价:%.2f 上月销量:%d", brand, model, seats, color, unitPrice, lastMonthSales);
}
}
import java.util.Scanner;
public class CarTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入汽车数量:");
int num = scanner.nextInt();
Car[] cars = new Car[num];
for (int i = 0; i < num; i++) {
System.out.println("请输入第" + (i + 1) + "辆汽车的品牌:");
String brand = scanner.next();
System.out.println("请输入型号:");
String model = scanner.next();
System.out.println("请输入座位数:");
int seats = scanner.nextInt();
System.out.println("请输入颜色:");
String color = scanner.next();
System.out.println("请输入单价:");
double unitPrice = scanner.nextDouble();
System.out.println("请输入上月销售量:");
int lastMonthSales = scanner.nextInt();
cars[i] = new Car(brand, model, seats, color, unitPrice, lastMonthSales);
}
System.out.println("共输入了" + num + "辆汽车,以下是车辆信息:");
System.out.println("\n品牌 型号 座位数 颜色 单价 上月销量 月销售金额");
for (Car car : cars) {
double salesAmount = car.calculateSalesAmount();
System.out.println(car + " " + String.format("%.2f", salesAmount));
}
}
}
```
这份代码创建了一个 Car 类来封装汽车的各种属性,然后在 CarTest 类中实例化多部小车,通过键盘输入数据,最后以表格形式输出。
阅读全文