java定义数组存储手机
时间: 2023-08-21 10:07:33 浏览: 47
可以使用以下代码定义一个包含多个手机的数组:
```java
public class Phone {
private String brand;
private String model;
private int price;
// 构造方法
public Phone(String brand, String model, int price) {
this.brand = brand;
this.model = model;
this.price = price;
}
// get/set 方法省略
public static void main(String[] args) {
// 定义一个手机数组,存储三款不同品牌的手机
Phone[] phones = new Phone[3];
phones[0] = new Phone("Apple", "iPhone X", 6999);
phones[1] = new Phone("Samsung", "Galaxy S9", 5999);
phones[2] = new Phone("Huawei", "Mate 10", 4999);
// 遍历手机数组,输出手机信息
for (Phone phone : phones) {
System.out.println("品牌:" + phone.getBrand() + ",型号:" + phone.getModel() + ",价格:" + phone.getPrice());
}
}
}
```
上述代码中,我们使用 `Phone` 类来表示手机,定义了 `brand`(品牌)、`model`(型号)和 `price`(价格)三个属性,并提供了相应的构造方法和 get/set 方法。
在 `main` 方法中,我们定义了一个长度为 3 的 `Phone` 数组 `phones`,并在数组中存储了三款不同品牌的手机。最后,我们使用 for 循环遍历手机数组,输出了每个手机的品牌、型号和价格信息。