用java 编写有10个硬盘,有两个重要的属性:价格和容量。编写一个应用程序,分别按照价格和容量排序并输出10个硬盘的相应信息
时间: 2024-02-21 12:57:30 浏览: 130
好的,以下是 Java 代码实现:
```java
import java.util.Arrays;
import java.util.Comparator;
public class HardDisk {
private double price;
private double capacity;
public HardDisk(double price, double capacity) {
this.price = price;
this.capacity = capacity;
}
public double getPrice() {
return price;
}
public double getCapacity() {
return capacity;
}
public String toString() {
return "Price: " + price + ", Capacity: " + capacity;
}
public static void main(String[] args) {
HardDisk[] hardDisks = new HardDisk[10];
hardDisks[0] = new HardDisk(100, 500);
hardDisks[1] = new HardDisk(50, 250);
hardDisks[2] = new HardDisk(200, 1000);
hardDisks[3] = new HardDisk(75, 375);
hardDisks[4] = new HardDisk(150, 750);
hardDisks[5] = new HardDisk(225, 1125);
hardDisks[6] = new HardDisk(120, 600);
hardDisks[7] = new HardDisk(90, 450);
hardDisks[8] = new HardDisk(180, 900);
hardDisks[9] = new HardDisk(60, 300);
// 按价格排序
Arrays.sort(hardDisks, Comparator.comparing(HardDisk::getPrice));
System.out.println("按价格排序:");
for (HardDisk hardDisk : hardDisks) {
System.out.println(hardDisk.toString());
}
// 按容量排序
Arrays.sort(hardDisks, Comparator.comparing(HardDisk::getCapacity));
System.out.println("按容量排序:");
for (HardDisk hardDisk : hardDisks) {
System.out.println(hardDisk.toString());
}
}
}
```
这个程序定义了一个 HardDisk 类,包含价格和容量两个属性,以及按价格和容量排序的方法。在 main 方法中,创建了 10 个 HardDisk 对象,并调用了排序方法,最后输出了排序结果。
阅读全文