调查所在小组或所在宿舍每位同学的手机信息,定义一个手机类,初始化手机(数组)数据(最少三部手机),输出每位同学手机的信息及手机的日常功能。要求:在下面示范程序的基础上增加一些成员变量和成员方法,实现更加丰富的功能。另外,增加功能:输出价格最低的手机信息
时间: 2024-11-15 07:23:14 浏览: 20
首先,我们可以定义一个名为`StudentPhone`的手机类,包含必要的属性如品牌、型号、操作系统、价格等,以及描述手机功能的一些方法。示例程序如下:
```java
public class StudentPhone {
// 成员变量
private String brand;
private String model;
private String os;
private double price;
// 构造函数
public StudentPhone(String brand, String model, String os, double price) {
this.brand = brand;
this.model = model;
this.os = os;
this.price = price;
}
// 获取手机信息的方法
public void showInfo() {
System.out.println("手机品牌:" + brand);
System.out.println("手机型号:" + model);
System.out.println("操作系统:" + os);
System.out.println("价格:" + price);
}
// 获取价格最低的手机信息的方法
public static StudentPhone findCheapest(StudentPhone[] phones) {
if (phones == null || phones.length == 0) {
return null;
}
StudentPhone cheapestPhone = phones[0];
for (StudentPhone phone : phones) {
if (phone.getPrice() < cheapestPhone.getPrice()) {
cheapestPhone = phone;
}
}
return cheapestPhone;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
// 初始化手机数组
StudentPhone[] studentPhones = new StudentPhone[3];
studentPhones[0] = new StudentPhone("苹果", "iPhone 13", "iOS", 8999.0);
studentPhones[1] = new StudentPhone("华为", "P40 Pro+", "EMUI", 7999.0);
studentPhones[2] = new StudentPhone("小米", "Mi 11 Ultra", "MIUI", 6999.0);
// 输出每位同学的手机信息
for (int i = 0; i < studentPhones.length; i++) {
System.out.println("学生" + (i+1) + "的手机:");
studentPhones[i].showInfo();
}
// 找出价格最低的手机并输出信息
StudentPhone cheapest = StudentPhone.findCheapest(studentPhones);
if (cheapest != null) {
System.out.println("最便宜的手机信息:");
cheapest.showInfo();
} else {
System.out.println("没有手机信息");
}
}
}
```
在这个例子中,我们增加了`price`成员变量表示手机价格,并添加了`findCheapest`静态方法来找出数组中最便宜的手机。运行这个程序,可以获取每位同学的手机信息以及价格最低的手机信息。
阅读全文
相关推荐
















