用java写一个 定义数组存储3部汽车对象。 汽车的属性:品牌,价格,颜色。 创建三个汽车对象,数据通过键盘录入而来,并把数据存入到数组当中。
时间: 2024-05-24 18:11:19 浏览: 110
java中用数组为一个类定义多个对象
4星 · 用户满意度95%
import java.util.Scanner;
public class CarArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Car[] cars = new Car[3]; // 定义长度为3的汽车数组
// 循环录入汽车信息
for (int i = 0; i < 3; 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();
// 创建汽车对象并存入数组
Car car = new Car(brand, price, color);
cars[i] = car;
}
// 输出汽车信息
for (Car car : cars) {
System.out.println(car.getBrand() + " " + car.getPrice() + " " + car.getColor());
}
}
}
class Car {
private String brand; // 品牌
private double price; // 价格
private String color; // 颜色
public Car(String brand, double price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
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;
}
}
阅读全文