//1. 定义"汽车"类,Car,包含以下成员: //1.1 成员属性: brand (品牌):String 类型, price (价格):int 类型,属性使用 private //修饰,为所有属性提供 set/get 方法 //2. 定义测试类,在测试类中的 main 函数中完成: //2.1 实例化 4 个 Car 对象,4 个对象的属性分别为:"Auto" 25 ,”Audi” 500,"Benz" //700,”BMW” 400 //2.2 创建一个 ArrayList 集合,分别将上面的 4 个 Car 对象添加到集合中 //2.3 获取集合中元素的品牌为“B”开头的所有汽车价格总和,并在控制台打印输出
时间: 2024-01-01 22:03:50 浏览: 113
//首先定义汽车类Car:
public class Car {
private String brand;
private int price;
public void setBrand(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
}
//在测试类中的main函数中完成:
import java.util.ArrayList;
public class TestCar {
public static void main(String[] args) {
//实例化4个Car对象
Car car1 = new Car();
car1.setBrand("Auto");
car1.setPrice(25);
Car car2 = new Car();
car2.setBrand("Audi");
car2.setPrice(500);
Car car3 = new Car();
car3.setBrand("Benz");
car3.setPrice(700);
Car car4 = new Car();
car4.setBrand("BMW");
car4.setPrice(400);
//创建一个ArrayList集合,将4个Car对象添加到集合中
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(car1);
carList.add(car2);
carList.add(car3);
carList.add(car4);
//获取集合中元素的品牌为"B"开头的所有汽车价格总和,并在控制台打印输出
int totalPrice = 0;
for (Car car : carList) {
if (car.getBrand().startsWith("B")) {
totalPrice += car.getPrice();
}
}
System.out.println("品牌为\"B\"开头的所有汽车价格总和为:" + totalPrice);
}
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)