java列出3个手机信息并比较价格大小
时间: 2024-11-17 09:30:36 浏览: 5
在Java中,我们可以创建一个简单的类如Phone,包含品牌、型号和价格属性,然后通过ArrayList存储一些Phone对象,并利用Collections.sort()方法按照价格排序。以下是简化的例子:
```java
import java.util.ArrayList;
import java.util.Collections;
class Phone {
String brand;
String model;
double price;
public Phone(String brand, String model, double price) {
this.brand = brand;
this.model = model;
this.price = price;
}
@Override
public String toString() {
return "Phone{" +
"brand='" + brand + '\'' +
", model='" + model + '\'' +
", price=" + price +
'}';
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Phone> phones = new ArrayList<>();
phones.add(new Phone("华为", "P40", 5999));
phones.add(new Phone("苹果", "iPhone 13", 7999));
phones.add(new Phone("小米", "Mi 11", 3999));
// 按照价格排序
Collections.sort(phones, (a, b) -> Double.compare(a.price, b.price));
for (Phone phone : phones) {
System.out.println(phone);
}
// 比较价格大小,这里直接用for循环遍历比较
for (int i = 0; i < phones.size() - 1; i++) {
if (phones.get(i).price > phones.get(i + 1).price) {
System.out.println("电话" + (i + 1) + ": " + phones.get(i + 1).toString() + " 的价格比 " + phones.get(i).toString() + " 更便宜");
} else {
System.out.println("电话" + (i + 1) + ": " + phones.get(i).toString() + " 的价格更贵");
}
}
}
}
```
阅读全文