用Java写一个按名称查找供应商信息的代码
时间: 2023-06-20 07:07:21 浏览: 49
假设我们有一个供应商类 `Supplier`,包含属性 `name`, `address`, `phone` 等信息,我们可以通过一个 `SupplierService` 类来实现按名称查找供应商信息的功能。以下是一个简单的示例代码:
```java
import java.util.ArrayList;
import java.util.List;
public class Supplier {
private String name;
private String address;
private String phone;
public Supplier(String name, String address, String phone) {
this.name = name;
this.address = address;
this.phone = phone;
}
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public class SupplierService {
private List<Supplier> suppliers;
public SupplierService() {
suppliers = new ArrayList<>();
suppliers.add(new Supplier("Supplier A", "Address A", "1234567890"));
suppliers.add(new Supplier("Supplier B", "Address B", "2345678901"));
suppliers.add(new Supplier("Supplier C", "Address C", "3456789012"));
}
public Supplier findSupplierByName(String name) {
for (Supplier supplier : suppliers) {
if (supplier.getName().equals(name)) {
return supplier;
}
}
return null; // supplier not found
}
}
```
在上面的代码中,我们定义了一个 `SupplierService` 类,它包含一个 `suppliers` 列表,存储了供应商的信息。在构造函数中,我们初始化了一些供应商信息,以便测试使用。
`SupplierService` 类提供了一个 `findSupplierByName` 方法,它接收一个名称参数 `name`,并在 `suppliers` 列表中查找与名称匹配的供应商信息。如果找到了,则返回该供应商对象;否则返回 `null`。