用Java定义数组存储3部手机对象。手机的属性:品牌,价格,颜色。要求:创建三个手机对象,数据通过键盘录入而来,并把数据存入到数组当中,计算出三部手机的平均价格
时间: 2024-03-23 19:39:37 浏览: 104
好的,以下是Java代码:
```java
import java.util.Scanner;
public class Phone {
private String brand;
private double price;
private String color;
public Phone(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;
}
}
public class PhoneTest {
public static void main(String[] args) {
Phone[] phones = new Phone[3];
Scanner scanner = new Scanner(System.in);
double totalPrice = 0;
for (int i = 0; i < 3; i++) {
System.out.println("请输入手机品牌:");
String brand = scanner.next();
System.out.println("请输入手机价格:");
double price = scanner.nextDouble();
System.out.println("请输入手机颜色:");
String color = scanner.next();
Phone phone = new Phone(brand, price, color);
phones[i] = phone;
totalPrice += price;
}
double averagePrice = totalPrice / 3;
System.out.println("三部手机的平均价格为:" + averagePrice);
}
}
```
在上面的代码中,我们定义了一个 Phone 类来表示手机,包含品牌、价格和颜色三个属性。然后在 PhoneTest 类中,我们使用数组来存储三部手机对象,并通过键盘录入获取每部手机的品牌、价格和颜色信息,将其存入数组中,并计算出三部手机的平均价格。最后将平均价格输出到控制台。
阅读全文