第四色 展示何如界说一个 Product 类_price_name_字符串
诚然第四色,底下是一个完好的示例,展示何如界说一个 Product 类,并将字符串列表退换为 Product 对象列表。这个示例包括类的界说和退换逻辑的已毕。
java
import ;
import java.util.List;
// 界说 Product 类
class Product {
private String name;
private double price;
// 构造函数
public Product(String name, double price) {
this.name = name;
this.price = price;
}
伸开剩余84%// Getter 要津(可选,字据需要添加)
public String getName() {
return name;
}
public double getPrice() {
return price;
}
// 重写 toString 要津以便于输出对象信息
@Override
public String toString() {
return "Product{name='" + name + "', price=" + price + "}";
}
}
// 主类第四色,成人卡通动漫包含退换逻辑
public class StringListToProductList {
public static void main(String[] args) {
// 示例字符串列表
List<String> stringList = List.of(
"Laptop:1200.00",
"Smartphone:800.00",
"Tablet:500.00"
);
// 退换字符串列表为 Product 对象列表
List<Product> productList = convertStringToProductList(stringList);
// 输分娩物列表
for (Product product : productList) {
System.out.println(product);
}
}
// 将字符串列表退换为 Product 对象列表的要津
public static List<Product> convertStringToProductList(List<String> stringList) {
List<Product> productList = new ArrayList<>();
计算器在线使用for (String str : stringList) {
String[] parts = str.split(":");
if (parts.length == 2) {
String name = parts[0];
double price = Double.parseDouble(parts[1]);
productList.add(new Product(name, price));
} else {
// 处置局势不正确的字符串,举例记载日记或抛出十分
System.err.println("Invalid format: " + str);
}
}
return productList;
}
}
代码施展
Product 类:
包含两个独到字段:name 和 price。
提供一个构造函数用于运行化这些字段。
提供了 getName 和 getPrice 要津(可选),以便在需要时造访这些字段。
重写了 toString 要津,以便于输出对象信息。
StringListToProductList 类:
包含 main 要津,用于演示退换历程。
界说了一个示例字符串列表 stringList。
调用 convertStringToProductList 要津将字符串列表退换为 Product 对象列表。
遍历并输出 Product 对象列表。
convertStringToProductList 要津:
给与一个字符串列表看成参数。
遍历字符串列表,使用 split(":") 要津将每个字符串分割为称呼和价钱。
搜检分割后的数组长度是否为 2,以确保局势正确。
领路称呼和价钱,并创建 Product 对象。
将 Product 对象添加到效力列表中。
复返退换后的 Product 对象列表。
通过这种表情第四色,你不错空闲地将字符串列表退换为自界说对象列表,并字据需要处置局势不正确的字符串。
发布于:浙江省